Python timezone processing

Question:

Given:
date as a string ‘2022-12-28T20:55:45Z’

Z in the end indicates the UTC as I understand.
The VM tz is Europe/Paris.

import datetime as dt
print(dt.datetime.strptime('2022-12-28T20:55:45Z', '%Y-%m-%dT%H:%M:%S%z').strftime('%s'))
1672257345

Which is December 28, 2022 7:55:45 PM UTC
So this is a hour behind the actual string date.

Explicitly defining the offset doesn’t change anything.

    print(dt.datetime.strptime('2022-12-28T20:55:45+0000', '%Y-%m-%dT%H:%M:%S%z').strftime('%s'))
    1672257345
    print(dt.datetime.strptime('2022-12-28T20:55:45+1200', '%Y-%m-%dT%H:%M:%S%z').strftime('%s'))
    1672257345

I don’t understand how this is possible.
20:55:45+1200 shall be equal to 08:55:45+0000 but python returns me the same epoch.

Tried pytz with the same result

    import pytz
    cet = timezone('CET')
    k = timezone('Europe/Kiev')
    a=dt.datetime.strptime('2022-12-28T20:55:45', '%Y-%m-%dT%H:%M:%S')
    cet.localize(a).strftime('%s')
   '1672257345'
   k.localize(a).strftime('%s')
   '1672257345'
Asked By: Egor

||

Answers:

Not sure where .strftime('%s') is coming from. %s isn’t a valid format code and gives ValueError: Invalid format string, but .timestamp() gives different numbers for the different time zones:

import datetime as dt
a = dt.datetime.strptime('2022-12-28T20:55:45Z', '%Y-%m-%dT%H:%M:%S%z')
print(a, a.timestamp())
b = dt.datetime.strptime('2022-12-28T20:55:45+0000', '%Y-%m-%dT%H:%M:%S%z')
print(b, b.timestamp())
c = dt.datetime.strptime('2022-12-28T20:55:45+1200', '%Y-%m-%dT%H:%M:%S%z')
print(c, c.timestamp())
print((b.timestamp() - c.timestamp()) / 3600)

Output:

2022-12-28 20:55:45+00:00 1672260945.0
2022-12-28 20:55:45+00:00 1672260945.0
2022-12-28 20:55:45+12:00 1672217745.0
12.0

(12-hour difference as expected)

Answered By: Mark Tolonen
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.