Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign timezone to a Python datetime [duplicate]

Assume that I have a timezone-less datetime object:

import datetime
import pytz
fmt = "%Y-%m-%d %H:%M:%S %Z%z"
dtUnaware = datetime.datetime(1979,2,20,6)
print(dtUnaware.strftime(fmt))

This yields:

1979-02-20 06:00:00 

So far, so good. Now, I want to assign a timezone to this object. It seems like I could use either datetime.replace or pytz.localize.

First:

dtAware1 = dtUnaware.replace(tzinfo=pytz.timezone('Asia/Jerusalem'))
print(dtAware1.strftime(fmt))

returns: 1979-02-20 06:00:00 LMT+0221. Secondly:

dtAware2 = pytz.timezone('Asia/Jerusalem').localize(dtUnaware, is_dst=None)
print(dtAware2.strftime(fmt))

returns 1979-02-20 06:00:00 IST+0200.

What's wrong with the first method? It seems to assign a wrong timezone. Am I doing something wrong?

like image 691
Dror Avatar asked Oct 31 '22 10:10

Dror


1 Answers

From Pytz documentation : This library differs from the documented Python API for tzinfo implementations; if you want to create local wallclock times you need to use the localize() method documented in this document... Unfortunately these issues cannot be resolved without modifying the Python datetime implementation (see PEP-431)

My reading of that is that a pytz timezone is not exactly the same thing as a standard timezone. If you had a genuine timezone, first method should be good, but you have not.

like image 152
Serge Ballesta Avatar answered Nov 04 '22 08:11

Serge Ballesta