python - 以 3 位毫秒的日期时间对象的形式读入字符串

标签 python python-3.x datetime

我正在读取日期时间格式的字符串。但是,毫秒不是有 6 位数字,而是只有 3 位数字,末尾有一个字母 Z。我如何读入这个字符串并使其成为日期时间对象,并添加 1 天,然后将其写成上述格式的字符串,即毫秒的 3 位数字和末尾的字母 Z。我尝试了以下代码但没有成功:

old_date= "2018-06-06T23:59:59.999Z"
new_date = datetime.datetime.strptime(old_date, '%Y-%m-%d %H:%M:%S.%f%Z') + datetime.timedelta(days=1)
print(new_date)

最佳答案

你应该使用这种格式

datetime.datetime.strptime(old_date, '%Y-%m-%dT%H:%M:%S.%fZ')
Out[180]: datetime.datetime(2018, 6, 6, 23, 59, 59, 999000)

更新

dt1=datetime.datetime.strptime(old_date, '%Y-%m-%dT%H:%M:%S.%fZ')+datetime.timedelta(days=1)
dt1.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]+'Z'
Out[196]: '2018-06-07 23:59:59.999Z'

关于python - 以 3 位毫秒的日期时间对象的形式读入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53404692/

相关文章:

python - Django 1.9 URLField 删除必要的 http ://prefix

python - 将时间舍入到最近的小时python

c# - 将 DateTime 转换为格式为 YYYYMMDD 的字符串

python - PyInstaller 和 OpenEXR - exe 崩溃

python - 使用线程和扭曲发送消息的高速公路

python - 如果我想在 Ubuntu 上将 Python 2 与 Django 一起使用,如何安装 Python 3

Python:字符串无法识别达到一定数量的两位数

SQL - 比较 WHERE 语句中的日期在 Access DB 中无法正常工作

python - 如何让Windows自动为文件添加扩展名?

python - 将脚本升级到 Python 3 -\r\n & 文本二进制模式