I have a string formatted date 2021-12-14T12:05:51.8031499
How can I get the Epoch value of this?
CodePudding user response:
dateutil is your friend, also with 7 digits of fractional seconds:
from dateutil.parser import isoparse
isoparse("2021-12-14T12:05:51.8031499")
Out[2]: datetime.datetime(2021, 12, 14, 12, 5, 51, 803149)
isoparse("2021-12-14T12:05:51.8031499").timestamp()
Out[3]: 1639479951.803149
Note: given ISO format date/time will result in a naive datetime object, which Python will treat as local time, i.e. it will be converted from your machine's local time setting to UTC before Unix time is calculated for timestamp()
!
CodePudding user response:
Parse date string to datetime object then use utcfromtimestamp() function to return the epoch time from it.
Note there is one extra digit in the example time. Expected microseconds in Python datetime is 6 digits not 7 (e.g. 803149).
from datetime import datetime, timezone
d = '2021-12-14T12:05:51.803149'
dt = datetime.strptime(d, '%Y-%m-%dT%H:%M:%S.%f')
print(dt)
# convert datetime to time-aware timezone at UTC
# so correct timestamp is returned
dt = dt.replace(tzinfo=timezone.utc)
# Return the time in seconds since the epoch
seconds_since_epoch = dt.timestamp()
print(seconds_since_epoch)
# convert epoch back to datetime object
d2 = datetime.utcfromtimestamp(seconds_since_epoch)
print(d2)
Output:
2021-12-14 12:05:51.803149
1639483551.803149
2021-12-14 12:05:51.803149