I have a string formatted date 2021-12-14T12:05:51.8031499
How can I get the Epoch value of this?
Asked
Active
Viewed 3,101 times
0

FObersteiner
- 22,500
- 8
- 42
- 72

VVictor
- 249
- 3
- 10
-
Does this answer your question? [How do I translate an ISO 8601 datetime string into a Python datetime object?](https://stackoverflow.com/questions/969285/how-do-i-translate-an-iso-8601-datetime-string-into-a-python-datetime-object) – Khinza Dec 14 '21 at 15:19
-
Looks like your timestamp has too many microseconds to be valid – Chris Dec 14 '21 at 15:21
2 Answers
3
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()
!

FObersteiner
- 22,500
- 8
- 42
- 72
2
Parse date string to datetime object then use utcfromtimestamp() function to return the epoch time from it. Can also call datetime.fromtimestamp(time, tz=timezone.utc)
.
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-zone aware datetime 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)
# this creates a timezone-aware datatime
d3 = datetime.fromtimestamp(seconds_since_epoch, tz=timezone.utc)
print(d3)
Output:
2021-12-14 12:05:51.803149
1639483551.803149
2021-12-14 12:05:51.803149
2021-12-14 12:05:51.803149+00:00
Note calling fromtimestamp()
with tz argument creates a timezone-aware datetime object. Note "+00:00" suffix in output means UTC.

CodeMonkey
- 22,825
- 4
- 35
- 75