Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python datetime object show wrong timezone offset

I am try creating a datetime object in python using datetime and pytz, the offset shown is wrong.

import datetime from pytz import timezone  start = datetime.datetime(2011, 6, 20, 0, 0, 0, 0, timezone('Asia/Kolkata')) print start 

The output shown is

datetime.datetime(2011, 6, 20, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' HMT+5:53:00 STD>) 

Note that 'Asia/Kolkata' is IST which is GMT+5:30 and not HMT+5:53. This is a standard linux timezone, why do I get this wrong, and how do I solve it?

like image 487
compbugs Avatar asked Jun 20 '11 12:06

compbugs


People also ask

How do I remove Tzinfo from datetime?

To remove timestamp, tzinfo has to be set None when calling replace() function. First, create a DateTime object with current time using datetime. now(). The DateTime object was then modified to contain the timezone information as well using the timezone.

Is Python datetime timezone aware?

Timezone-aware objects are Python DateTime or time objects that include timezone information. An aware object represents a specific moment in time that is not open to interpretation.

Does pytz handle DST?

Localized times and date arithmetic This library also allows you to do date arithmetic using local times, although it is more complicated than working in UTC as you need to use the normalize() method to handle daylight saving time and other timezone transitions.

How do I remove the timezone from a date object?

There are multiple ways to remove the local time zone from a date: Use the toUTCString() method to convert the date to a string using UTC. Use the toLocaleDateString() method to format the date according to a specific locale. Format the date and time consistently, e.g. as YYYY-MM-DD hh:mm:ss .


1 Answers

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 use localize or astimezone instead of passing a timezone object to datetime.datetime.

like image 90
Ferdinand Beyer Avatar answered Sep 23 '22 03:09

Ferdinand Beyer