0

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

2

2 Answers 2

4

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() !

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.