0

I have a string formatted date 2021-12-14T12:05:51.8031499 How can I get the Epoch value of this?

FObersteiner
  • 16,957
  • 5
  • 24
  • 56
VVictor
  • 173
  • 9
  • 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 Answers2

1

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
CodeMonkey
  • 20,521
  • 4
  • 28
  • 71
1

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
  • 16,957
  • 5
  • 24
  • 56