未转换的数据仍然是:Python中的.387000

The*_*ion 8 python strftime strptime

我的日期时间是我从文本文件中读取的字符串.我想减少额外的毫秒数,但我想首先将它转换为日期时间变量.这是因为它可能采用不同的格式,具体取决于文本文件中的内容.然而,我所尝试的一切都希望我已经知道格式.请看看我在这里尝试的内容:

import time, datetime

mytime = "2015-02-16 10:36:41.387000"
myTime = time.strptime(mytime, "%Y-%m-%d %H:%M:%S.%f")

myFormat = "%Y-%m-%d %H:%M:%S"

print datetime.datetime.fromtimestamp(time.mktime(time.strptime(mytime, myFormat)))
Run Code Online (Sandbox Code Playgroud)

但这给了我这个错误:

File "python", line 10, in <module>
ValueError: unconverted data remains: .387000`
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我如何做一个正常的日期时间格式?在其他语言中,我可以传递各种格式,然后将其设置为新格式​​而不会出现问题.

Sel*_*cuk 22

你正在倒退.试试这个:

from datetime import datetime

mytime = "2015-02-16 10:36:41.387000"
myTime = datetime.strptime(mytime, "%Y-%m-%d %H:%M:%S.%f")

myFormat = "%Y-%m-%d %H:%M:%S"

print "Original", myTime
print "New", myTime.strftime(myFormat)
Run Code Online (Sandbox Code Playgroud)

结果:

Original 2015-02-16 10:36:41.387000
New 2015-02-16 10:36:41
Run Code Online (Sandbox Code Playgroud)


Mau*_*ldi 5

你忘了引用微秒 myFormat

myFormat = "%Y-%m-%d %H:%M:%S.%f"
Run Code Online (Sandbox Code Playgroud)

无论如何,你可以用更少的步骤转换它

from datetime import datetime

mytime = "2015-02-16 10:36:41.387000"
full = "%Y-%m-%d %H:%M:%S.%f"
myTime = datetime.strptime(mytime, full)
>>> datetime.datetime(2015, 2, 16, 10, 36, 41, 387000)
Run Code Online (Sandbox Code Playgroud)

这里mytimedatetime对象。如果您想在没有微秒的情况下打印,请使用strftime

myfmt = "%Y-%m-%d %H:%M:%S"
print datetime.strptime(mytime, full).strftime(myfmt)
>>> 2015-02-16 10:36:41
Run Code Online (Sandbox Code Playgroud)