0

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?

x89
  • 2,798
  • 5
  • 46
  • 110
  • you are looking for `strptime` not `strtotime` – 2e0byo Oct 22 '21 at 11:54
  • https://stackoverflow.com/questions/10494312/parsing-time-string-in-python – 2e0byo Oct 22 '21 at 11:55
  • try `.timestamp()` method to get the epoch time of a datetime object – Ghost Ops Oct 22 '21 at 11:55
  • str doesn't have a timestamp() attribute. Is it a function from the datetime module? @GhostOps – x89 Oct 22 '21 at 12:05
  • What do I put as the second argument if I use striptime? ```time = datetime.datetime.strptime(lastModified)``` – x89 Oct 22 '21 at 12:07
  • check [this](https://docs.python.org/3/library/datetime.html?highlight=timestamp#datetime.datetime.timestamp) to know about `.timestamp()` method of datetime object – Ghost Ops Oct 22 '21 at 12:07

1 Answers1

1

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

FObersteiner
  • 22,500
  • 8
  • 42
  • 72