2

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).

Joe
  • 11,983
  • 31
  • 109
  • 183
  • 1
    Possible partial duplicate of [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – wjandrea Jul 09 '19 at 16:51
  • Possible partial duplicate of [Convert python datetime to epoch with strftime](https://stackoverflow.com/q/11743019/4518341) – wjandrea Jul 09 '19 at 16:53
  • 1
    The *epoch* timestamp is `0`. You mean you want a Unix timestamp - that is, a timestamp that is *based* on the Unix epoch (`1970-01-01T00:00:00Z`). https://codeofmatt.com/please-dont-call-it-epoch-time/ – Matt Johnson-Pint Jul 09 '19 at 17:08
  • Correct. But at the end of day - all I want is to compare that Zulu timestamp with current timestamp on my machine.. – Joe Jul 09 '19 at 19:46

2 Answers2

2
  1. Use time.strptime() to parse your date string.
  2. If you're working with local times, use 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)
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
  • So this unix_timestamp should be epoch time from UTC? Then to see current time - I can use maybe `int(time.time())` and compare the 2? – Joe Jul 09 '19 at 17:01
  • 1
    @Joe If your datetime is in UTC, you should use [`calendar.timegm()`](https://docs.python.org/3/library/calendar.html#calendar.timegm) instead of `time.mktime()`. As suggested [here](https://docs.python.org/3/library/time.html). – Ronan Boiteau Jul 09 '19 at 17:11
  • My datetime is EST. Should I convert to UTC in order to compare? – Joe Jul 09 '19 at 17:20
1

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.

nthall
  • 2,847
  • 1
  • 28
  • 36