Home > Net >  how to use strtotime to convert time stamp into unixepoch timestamp
how to use strtotime to convert time stamp into unixepoch timestamp

Time:10-23

I have a datetime string 2021-10-20 15:42:40 00:00that I obtain via S3

s3_object = s3_resource.Object("testunzipping", "DataPump_10000838.zip")
lastModified = s3_object.last_modified
lastModified = str(lastModified)

I need to convert it into a unixepochtimestamp. I was trying this after reading another SO answer

import datetime
time = datetime.datetime.strtotime(lastModified)

but I get this error:

"type object 'datetime.datetime' has no attribute 'strtotime'"

How else can I convert the str or the datetime object into a unixepochtimestamp?

CodePudding user response:

Using fromisoformat (Python 3.7 ):

import datetime
lastModified = "2021-10-20 15:42:40 00:00"
ts = datetime.datetime.fromisoformat(lastModified).timestamp()
print(ts)
# 1634744560.0 # Unix time in seconds

Using strptime:

import datetime
lastModified = "2021-10-20 15:42:40 00:00"
ts = datetime.datetime.strptime(lastModified, "%Y-%m-%d %H:%M:%S%z").timestamp()
print(ts)
# 1634744560.0 # Unix time in seconds

Caveat: the input here has a UTC offset ( 00:00), which, if parsed correctly, will give aware datetime. All fine then. If that is not the case (no UTC offset or time zone specified), you'll end up with naive datetime, which Python treats as local time. Thus if you call .timestamp(), it will be converted to UTC first (since Unix time refers to UTC).

  • Related