I have one timezone's offset from UTC in seconds (19800
) and also have it in string format - +0530
.
How do I use them to create a tzinfo
instance? I looked into pytz
, but there I could only find APIs that take timezone name as input.
I have one timezone's offset from UTC in seconds (19800
) and also have it in string format - +0530
.
How do I use them to create a tzinfo
instance? I looked into pytz
, but there I could only find APIs that take timezone name as input.
If you can, take a look at the excellent dateutil package instead of implementing this yourself.
Specifically, tzoffset. It's a fixed offset tzinfo
instance initialized with offset
, given in seconds, which is what you're looking for.
Update
Here's an example. Be sure to run pip install python-dateutil
first.
from datetime import datetime
from dateutil import tz
# First create the tzinfo object
tzlocal = tz.tzoffset('IST', 19800)
# Now add it to a naive datetime
local = naive.replace(tzinfo=tzlocal)
# Or convert another timezone to it
utcnow = datetime.utcnow().replace(tzinfo=tz.tzutc())
now = utcnow.astimezone(tzlocal)
I looked up the name IST
from here. The name can really be anything. Just be careful if you deviate, since if you use code that relies on the name, it could lead to bugs later on.
By the way, if you have the timezone name upfront, and your operating system supports it, you can use gettz instead:
# Replace the above with this
tzlocal = tz.gettz('IST')