I have a timestamp in a file as:
2019-07-09T16:33:45Z
How to convert it to epoch time in Python 3?
Eventually I want to compare that Zulu timestamp with a current EST time (if is older than current time or not).
I have a timestamp in a file as:
2019-07-09T16:33:45Z
How to convert it to epoch time in Python 3?
Eventually I want to compare that Zulu timestamp with a current EST time (if is older than current time or not).
time.strptime()
to parse your date string.time.mktime()
to get the Unix timestamp in your timezone. Or use calendar.timegm()
if you're working with UTC times.Example:
import time
import calendar
timestamp = time.strptime("2019-07-09T16:33:45Z", "%Y-%m-%dT%H:%M:%SZ")
unix_time_local = time.mktime(timestamp)
unix_time_utc = calendar.timegm(timestamp)
I'm not familiar with Zulu time but the internet suggests that it's the same as UTC.
There are other date/time libraries (arrow
is a popular one recently) but in python3 this can be done using the builtin datetime
using two functions: strptime and timestamp
Here's a quick example solution:
import datetime
time_string = "2019-07-09T16:33:45Z"
parsed_datetime = datetime.strptime(time_string, "%Y-%m-%dT%H:%M:%SZ")
unixtime = parsed_datetime.timestamp()
Note that datetime.timestamp()
returns a float.
Also might be worth noting that for comparison, converting from datetime object to unixtime isn't even necessary - you can simply compare two datetime objects directly like dt1 < dt2
.