bjem
bjem

Reputation: 195

Python seeming to incorrectly handle time zone conversions

I am confused by the following behaviour in a python program I am writing to convert dates and times. I have data in raw `wall clock time' as New Zealand Standard time, and want to convert it so that it is always UTC+12 (or GMT+12 as offered in pytz).

The problem is that when I run the program it gives results that seem incorrect. An example output is shown below. When the date of 24/07/2015 08:00 hours (8am 24th July 2015) is entered, defined as 'Pacific/Auckland', then converted to GMT+12 it seems to give an incorrect result that is one day earlier. I am not sure why this is, as the times should be exactly the same if my understanding of how the time zone conversions is correct.

Is anybody able to point out what I am doing wrong here?

The program output:

Pacific/Auckland
24/07/2015 08:00
23/07/2015 08:00

The `Minimal Working Example' source code:

#!/usr/bin/env python

import time
import pytz
import datetime

def main():

    time_zone = 'Pacific/Auckland'
    print(time_zone)

    local = pytz.timezone(time_zone)

    time_str = '24/07/2015 08:00'
    print(time_str)

    t = time.strptime(time_str, '%d/%m/%Y %H:%M')
    t_datetime = datetime.datetime.fromtimestamp(time.mktime(t))

    local_dt = local.localize(t_datetime)

    ds2 = local_dt.astimezone(pytz.timezone('Etc/GMT+12')).strftime('%d/%m/%Y %H:%M')

    print(ds2)


if __name__ == '__main__':
    # Parse the system arguments and get the busbar and input directory.
    main()

##### END OF FILE #####

Upvotes: 0

Views: 2060

Answers (1)

jfs
jfs

Reputation: 414585

POSIX style timezones ('Etc/GMT+h') have the opposite sign. You are converting from +1200 to -1200 that is in total 24 hours off that is why you get the same hour but the wrong day.

#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz

naive = datetime.strptime('24/07/2015 08:00', '%d/%m/%Y %H:%M')
aware = pytz.timezone('Pacific/Auckland').localize(naive, is_dst=None)
print(aware)
utc_dt = aware.astimezone(pytz.utc)
print(utc_dt)
# +1200
print(utc_dt.astimezone(pytz.timezone('Etc/GMT-12')))

Output

2015-07-24 08:00:00+12:00
2015-07-23 20:00:00+00:00
2015-07-24 08:00:00+12:00

Upvotes: 2

Related Questions