从Python中的datetime对象中删除毫秒

时间:2017-09-20 14:48:34

标签: python datetime

我试图在Python中从此字符串2017-09-12 22:33:55.28109中删除毫秒(28109)。

代码:

import datetime as dt
from datetime import date,datetime

created_date = datetime.fromtimestamp(ctime)
d=datetime.strptime(created_date, "%Y-%m-%d %H:%M:%S.%fZ")
created_date = datetime.strftime(d, "%m/%d/%Y %I:%M:%S %p")
print(created_date)

错误:

`d=datetime.strptime(created_date, "%Y-%m-%d %H:%M:%S.%fZ")`

TypeError: must be str, not datetime.datetime

2 个答案:

答案 0 :(得分:2)

已经拥有datetime对象,您无需再次解析它。 datetime.fromtimestamp()电话就足够了。

删除datetime.strptime()行。

created_date = datetime.fromtimestamp(ctime)
created_date = created_date.strftime("%m/%d/%Y %I:%M:%S %p")
print(created_date)

我还更改了您的strftime()来电,这是一种方法,您只需在datetime对象上调用它。

我怀疑您打印了datetime.fromtimestamp()来电的返回值,并感到困惑。 str() conversion of a datetime() instance将值格式化为ISO 8601 string。请注意,即使确实有字符串,您也使用了错误的格式(该字符串中没有时区,因此%Z不适用。)

如果您需要datetime对象而不是格式化字符串,您也可以将时间戳转换为整数;微秒在时间戳的小数部分中捕获:

>>> ctime = 1505252035.28109
>>> datetime.fromtimestamp(ctime)
datetime.datetime(2017, 9, 12, 22, 33, 55, 281090)
>>> datetime.fromtimestamp(int(ctime))
datetime.datetime(2017, 9, 12, 22, 33, 55)
>>> print(_)
2017-09-12 22:33:55

答案 1 :(得分:0)

您也可以使用time来实现您的目标。

import time
ctime = "2017-09-12 22:33:55.28109"
x = time.strptime(ctime.split('.')[0],'%Y-%m-%d %H:%M:%S')
x = time.strftime('%m/%d/%Y %I:%M:%S %p', x)
print (x)

'09 / 12/2017 10:33:55 PM'