Shorten UTC to UTC

How to convert form date time string Feb 25 2010, 16:19:20 CET to the unix era?

Currently my best approach is to use time.strptime() :

 def to_unixepoch(s): # ignore the time zone in strptime a = s.split() b = time.strptime(" ".join(a[:-1]) + " UTC", "%b %d %Y, %H:%M:%S %Z") # this puts the time_tuple(UTC+TZ) to unixepoch(UTC+TZ+LOCALTIME) c = int(time.mktime(b)) # UTC+TZ c -= time.timezone # UTC c -= {"CET": 3600, "CEST": 2 * 3600}[a[-1]] return c 

On other issues, I can see that calendar.timegm() and pytz could be used to simplify this, but they do not handle reduced time zones.

I need a solution that requires minimal redundant libraries, I like to stick to the standard library as much as possible.

+4
source share
1 answer

The Python standard library does not implement time zones. You should use python-dateutil . It provides useful extensions for the standard datetime module, including time zone implementations and an analyzer.

Using .astimezone(dateutil.tz.tzutc()) you can convert the time zones of datetime objects to UTC. For the current time as a timezone datetime object, you can use datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc()) .

 import dateutil.tz cet = dateutil.tz.gettz('CET') cesttime = datetime.datetime(2010, 4, 1, 12, 57, tzinfo=cet) cesttime.isoformat() '2010-04-01T12:57:00+02:00' cettime = datetime.datetime(2010, 1, 1, 12, 57, tzinfo=cet) cettime.isoformat() '2010-01-01T12:57:00+01:00' # does not automatically parse the time zone portion dateutil.parser.parse('Feb 25 2010, 16:19:20 CET')\ .replace(tzinfo=dateutil.tz.gettz('CET')) 

Unfortunately, this method will not be correct during the switch to daylight saving time.

+7
source

Source: https://habr.com/ru/post/1302381/


All Articles