How to add timezone into a naive datetime instance in python [duplicate]

Use tz.localize(d) to localize the instance. From the documentation: The first is to use the localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information): >>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0)) >>> print(loc_dt.strftime(fmt)) 2002-10-27 06:00:00 EST-0500 If you don’t use tz.localize(), but … Read more

Datetime Timezone conversion using pytz

I assume you have these questions: why does the first function work for UTC timezone? why does it fail for ‘US/Eastern’ timezone (DstTzInfo instance)? why does the second function work for all provided examples? The first function is incorrect because it uses d.replace(tzinfo=dsttzinfo_instance) instead of dsttzinfo_instance.localize(d) . The second function is correct most of the … Read more

Python datetime object show wrong timezone offset

See: http://bytes.com/topic/python/answers/676275-pytz-giving-incorrect-offset-timezone In the comments, someone proposes to use tzinfo.localize() instead of the datetime constructor, which does the trick. >>> tz = timezone(‘Asia/Kolkata’) >>> dt = tz.localize(datetime.datetime(2011, 6, 20, 0, 0, 0, 0)) >>> dt datetime.datetime(2011, 6, 20, 0, 0, tzinfo=<DstTzInfo ‘Asia/Kolkata’ IST+5:30:00 STD>) UPDATE: Actually, the official pytz website states that you should always … Read more

How do I get the UTC time of “midnight” for a given timezone?

I think you can shave off a few method calls if you do it like this: >>> from datetime import datetime >>> datetime.now(pytz.timezone(“Australia/Melbourne”)) \ .replace(hour=0, minute=0, second=0, microsecond=0) \ .astimezone(pytz.utc) BUT… there is a bigger problem than aesthetics in your code: it will give the wrong result on the day of the switch to or … Read more

How to make a timezone aware datetime object

In general, to make a naive datetime timezone-aware, use the localize method: import datetime import pytz unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0) aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC) now_aware = pytz.utc.localize(unaware) assert aware == now_aware For the UTC timezone, it is not really necessary to use localize since … Read more

Is there a list of Pytz Timezones?

You can list all the available timezones with pytz.all_timezones: In [40]: import pytz In [41]: pytz.all_timezones Out[42]: [‘Africa/Abidjan’, ‘Africa/Accra’, ‘Africa/Addis_Ababa’, …] There is also pytz.common_timezones: In [45]: len(pytz.common_timezones) Out[45]: 403 In [46]: len(pytz.all_timezones) Out[46]: 563