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?
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.
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.
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.
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 .
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With