Prithviraj Mitra Prithviraj Mitra - 6 months ago 49
Python Question

Removing miliseconds from datetime object in Python

I am trying to remove the miliseconds(28109) from this string

2017-09-12 22:33:55.28109
in Python.


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")


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

TypeError: must be str, not datetime.datetime

Any help is highly appreciated. Thanks in advance.

Answer Source

You already have a datetime object, you do not need to parse it again. The datetime.fromtimestamp() call was enough.

Remove the datetime.strptime() line.

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

I also changed your strftime() call, it is a method, you just call it on the datetime object you have.

I suspect that you printed the return value of the datetime.fromtimestamp() call, and got confused. The str() conversion of a datetime() instance formats the value as a ISO 8601 string. Note that even if you did have a string, you used the wrong format (there is no timezone in that string, so %Z does not apply).

If you needed a datetime object, rather than a formatted string, you could also just have converted your timestamp to an integer; the microseconds are captured in the decimal portion of the timestamp:

>>> 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download