Home > Software design >  python datetime timestamp conversion inconsistency
python datetime timestamp conversion inconsistency

Time:05-04

When I tried to convert a datetime object into timestamp and convert it back the result if off by 53 minutes.

timestamp = datetime.datetime(2022, 5, 3, 18, 0, 0, 0, tzinfo=pytz.timezone('US/Pacific')).timestamp()
# timetamp = 1651629180
datetime.datetime.fromtimestamp(timestamp, tz=pytz.timezone('US/Pacific'))
# formmated_timestamp = datetime.datetime(2022, 5, 3, 18, 53, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)

somehow the result is off by 53 minutes. This is true for all other values as well The issue seems to be at the .timestamp() part

CodePudding user response:

From the pytz docs:

This library only supports two ways of building a localized time. 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

The second way of building a localized time is by converting an existing localized time using the standard astimezone() method:

>>> ams_dt = loc_dt.astimezone(amsterdam)
>>> ams_dt.strftime(fmt)
'2002-10-27 12:00:00 CET 0100'

Unfortunately using the tzinfo argument of the standard datetime constructors ''does not work'' with pytz for many timezones.

>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt)
'2002-10-27 12:00:00 LMT 0020'
  • Related