>>> 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
.
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.
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.
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.
To remove timestamp, tzinfo has to be set None when calling replace() function.
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
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