0

I'm simply trying to take a naïve time, give it a local time zone, and then convert it into UTC.

I'm using the following code:

        create_time_local = parser.parse(timestring).replace(tzinfo=timezone('America/Chicago'))
        create_time_utc = create_time_local.astimezone(timezone('UTC'))

print('+++++++++' + timestring + '++++++++')
        print('*****************' + create_time_local.strftime(fmt) + '***************')
        print('-----' + create_time_utc.strftime(fmt) + '-----')

I can't figure out why, but here's the output:

+++++++++09/20/15 2:00:00 AM++++++++

*****************09/20/15 02:00:00 AM*************** -----09/20/15 07:51:00 AM-----

The correct answer, of course, should be 7:00 AM. I can't figure out why it's coming out 7:51 AM.


Alternate working code besides the linked code in the duplicate:

        create_time_local_naive = parser.parse(timestring)
        local_tz = timezone('America/Chicago')
        create_time_local = local_tz.localize(create_time_local_naive)
        create_time_utc = create_time_local.astimezone(timezone('UTC'))
Jeremy T
  • 758
  • 2
  • 9
  • 23
  • 1
    can you print timestring too? – sureshvv Sep 20 '15 at 17:18
  • @FoobieBletch It looks similar, but I don't think it's a duplicate because the answer is to create a naïve time zone, add the time zone, and then do the conversion, which is what I'm doing. – Jeremy T Sep 20 '15 at 17:38
  • Try using `pytz.utc.normallize()` to convert to utc instead of `.astimezone()` . – Anand S Kumar Sep 20 '15 at 17:42
  • Well, I stand corrected, thanks – Jeremy T Sep 20 '15 at 17:49
  • 1
    don't call `.replace(tzinfo=pytz_timezone)`; it may fail for any timezone with a non-fixed utc offset (many of them), use `pytz_timezone.localize(naive, is_dst=None)` instead. Related: [Datetime Timezone conversion using pytz](http://stackoverflow.com/q/27531718/4279) – jfs Sep 20 '15 at 19:12

0 Answers0