0

I have a datetime object that I need to convert to a given timezone and get the timezone offset at that date. Here's an example:

>>> datetime.datetime(2045,11,30, 0,0,0).strftime("%Y-%m-%dT%H:%M:%S")
'2045-11-30T00:00:00'

I would like to dynamically add in the offset for the timezone "America/Chicago", so for example, the result would look like:

'2045-11-30T00:00:00T-06:00' # fluctuates based on DST, cannot be hardcoded

How would I do this?

FI-Info
  • 635
  • 7
  • 16

1 Answers1

1

I believe what you are looking for is tzinfo. In the docs there is a working example of how it might work copied below:

>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
...     """A time zone with an arbitrary, constant -06:39 offset."""
...     def utcoffset(self, dt):
...         return timedelta(hours=-6, minutes=-39)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'
>>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat()
'2009-11-27T00:00:00.000100-06:39'

For your specific example the results look like:

>>> datetime(2045,11,30, 0,0,0, tzinfo=TZ()).isoformat()
'2045-11-30T00:00:00-06:00'

If you want to calculate in the DST offset into that TZ offset, you'll need to use the dst and there is a much longer example in the docs here on implementing both of these together.

MyNameIsCaleb
  • 4,409
  • 1
  • 13
  • 31
  • That has a hardcoded offset. The OP specifically asked for how to do this with a named time zone whose offset fluctuates and thus cannot be hardcoded. – Matt Johnson-Pint Oct 17 '19 at 18:18
  • @MattJohnson-Pint realized more what OP was asking after I originally answered which is why I edited in the bottom for how to do an offset based on DST and TZ together. – MyNameIsCaleb Oct 17 '19 at 18:19