rstk
rstk

Reputation: 25

Format timedelta as time zone offset string

As input I have two timestamp strings, one is a local time, other is the same moment in UTC time. I want to get the difference between them (basically to get local time zone offset) as string in specific format, e.g. +1100 or -0500.

import datetime

local = '2018-01-31 18:34:42.172'

utc = '2018-01-31 23:34:42.172'

local_dt = datetime.datetime.strptime(local, '%Y-%m-%d %H:%M:%S.%f')

utc_dt = datetime.datetime.strptime(utc, '%Y-%m-%d %H:%M:%S.%f')

offset_timedelta = local_dt - utc_dt

offset = offset_timedelta.total_seconds() / 3600

offset
Out[8]: -5.0

Using timedelta I can get offset as float (-5.0 for example above). From there I probably may create a function to turn that float to string in format I want, but I am curious if there's any datetime/timedelta method or formatting which I am missing, or some string format which would do the job with cleaner code and more efficient.

Any help would be appreciated.

edit, since I see my question is not clear: Is there a way to get "-0500" I need (string in that specific format, not a float), either by datetime library or string formatting?

Upvotes: 0

Views: 795

Answers (1)

BoarGules
BoarGules

Reputation: 16942

You've actually done all the work already. But you can use the module dateutil to hide the messy details:

>>> local = '2018-01-31 18:34:42.172'
>>> utc = '2018-01-31 23:34:42.172'

>>> from dateutil import parser, relativedelta
>>> tzh=relativedelta.relativedelta(parser.parse(local), parser.parse(utc))
>>> tzh
relativedelta(hours=-5)

To format it the way you want:

>>> f"{tzh.hours:+03d}{abs(tzh.minutes):02d}"
'-0500'

Or, Python 2.6 to 3.5:

>>> "{hours:+03d}{minutes:02d}".format(hours=tzh.hours, minutes=abs(tzh.minutes))
'-0500'

The module dateutil isn't in the standard library but it is well worth the trouble of downloading. It can do far, far more than this.

Upvotes: 1

Related Questions