I would like to get the timestamp from dates in the following formats:
Mon, 23 Nov 2020 19:00:00 GMT
Mon, 23 Nov 2020 20:00:00 +0100
I am using the the following statements to convert dates to datetime
objects:
dateobj = datetime.datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %Z')
dateobj = datetime.datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %z')
But using .timestamp()
method, different seconds from epoch are printed. Why doesn't the %Z
directive add timezone information to the datetime
object? How could I get the timezone into account, so the timestamp is equal?
Please note Inconsistent datetime parse timezone in Python . Your problem is %Z
, it makes strptime
accept certain strings (GMT, UTC and any value in time.tzname - docs ), but doesn't actually make anything out of it. The returned datetime object is naive - which is why Python will assume it's local time if you call the timestamp()
method of it.
You can use dateutil's parser instead:
from dateutil.parser import parse
for s in ("Mon, 23 Nov 2020 19:00:00 GMT", "Mon, 23 Nov 2020 20:00:00 +0100"):
dt = parse(s)
print(repr(dt), dt.timestamp())
# datetime.datetime(2020, 11, 23, 19, 0, tzinfo=tzutc()) 1606158000.0
# datetime.datetime(2020, 11, 23, 20, 0, tzinfo=tzoffset(None, 3600)) 1606158000.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.