2

I wanted to convert the iso datetime into epoch format using python datetime library.

Below is my code, but it's not working.

from datetime import datetime
epoch = datetime(1970, 1, 1)
last_updated_at = int((datetime.strptime('2020-10-16T09:29:26.580-07:00', '%Y-%m-%dT%H:%M:%S.%f %z') - epoch).total_seconds()) 

I'm getting below error

ValueError: time data '2020-09-01T12:47:54.863-07:00' does not match format '%Y-%m-%dT%H:%M:%S.%f %z'
steve
  • 362
  • 3
  • 16

1 Answers1

3

use fromisoformat and timestamp:

from datetime import datetime

last_updated_at = int(datetime.fromisoformat('2020-10-16T09:29:26.580-07:00').timestamp()) 
# last_updated_at
# 1602865766

btw. your strptime format is nearly correct, just a space too much. correct would have been '%Y-%m-%dT%H:%M:%S.%f%z'.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • @steve: it's pretty [efficient](https://stackoverflow.com/questions/13468126/a-faster-strptime), too. Just one more thing to keep in mind: when using `timestamp()`, make sure the `tzinfo` of the datetime object is set (which is the case in your example). Otherwise (naive datetime), Python will assume the date/time refers to local time - but timestamp will relate to UTC (as UNIX time is defined). – FObersteiner Oct 22 '20 at 17:15