Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does datetime give different timezone formats for the same timezone?

>>> now = datetime.datetime.now(pytz.timezone('Asia/Tokyo'))
>>> dt = datetime(now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, pytz.timezone('Asia/Tokyo'))
>>> now
datetime.datetime(2018, 9, 7, 16, 9, 24, 177751, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)
>>> dt = datetime(now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, pytz.timezone('Asia/Tokyo'))
>>> dt
datetime.datetime(2018, 9, 7, 16, 9, 24, 177751, tzinfo=<DstTzInfo 'Asia/Tokyo' LMT+9:19:00 STD>)

For now I got JST+9:00:00 and for dt I got LMT+9:19:00. I don't understand why datetime uses a different format.

When I compare the times they are different:

>>> now == dt
False

How can I convert LMT to JST so that now == dt is True? I need to use datetime(2018, 9, 7, 16, 9, 24, 177751, timezone('Asia/Tokyo')) and at the same time I want JST.

like image 328
Khaino Avatar asked Sep 07 '18 07:09

Khaino


People also ask

Does datetime include timezone?

A DateTime value defines a particular date and time. It includes a Kind property that provides limited information about the time zone to which that date and time belongs.

How do I change datetime to different time zones?

ToLocalTime method behaves identically to the DateTime. ToLocalTime method. It takes a single parameter, which is the date and time value, to convert. You can also convert the time in any designated time zone to local time by using the static ( Shared in Visual Basic) TimeZoneInfo.

What is Tzinfo datetime?

tzinfo is an abstract base class. It cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class. The instance of the tzinfo class can be passed to the constructors of the datetime and time objects.

How do I remove T and Z from timestamp in Python?

To remove timestamp, tzinfo has to be set None when calling replace() function.


1 Answers

As noted in a related question's answer, Never create datetime with timezone info by using datetime(). Instead, you should use localize to convert datetimes to JST after creating them in UTC.

>>> import pytz
>>> from datetime import datetime
>>>
>>> now = datetime.now(pytz.utc)
>>> dt = datetime(now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, pytz.utc)
>>> jst = pytz.timezone('Asia/Tokyo')
>>> jst.normalize(now)
datetime.datetime(2018, 9, 7, 20, 21, 44, 653897, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)
>>> jst.normalize(dt)
datetime.datetime(2018, 9, 7, 20, 21, 44, 653897, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)
>>> now == dt
True
like image 190
FThompson Avatar answered Oct 03 '22 20:10

FThompson