Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create tzinfo when I have UTC offset?

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.

like image 753
AppleGrew Avatar asked Jul 31 '13 16:07

AppleGrew


People also ask

How do you find the UTC offset in Python?

utcoffset() Method with Example. The utcoffset() function is used to return a timedelta object that represents the difference between the local time and UTC time. This function is used in used in the datetime class of module datetime. Here range of the utcoffset is “timedelta(hours=24) <= offset <= timedelta(hours=24)” ...

What is Tzinfo datetime?

tzinfo is an abstract base class. It cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class. The instance of the tzinfo class can be passed to the constructors of the datetime and time objects.


2 Answers

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') 
like image 71
Joe Avatar answered Oct 13 '22 20:10

Joe


With Python 3.2 or higher, you can do this using the builtin datetime library:

import datetime datetime.timezone(-datetime.timedelta(hours=5, minutes=30) 

To solve your specific problem, you could use regex:

sign, hours, minutes = re.match('([+\-]?)(\d{2})(\d{2})', '+0530').groups() sign = -1 if sign == '-' else 1 hours, minutes = int(hours), int(minute)  tzinfo = datetime.timezone(sign * datetime.timedelta(hours=hours, minutes=minutes)) datetime.datetime(2013, 2, 3, 9, 45, tzinfo=tzinfo) 
like image 27
Turtles Are Cute Avatar answered Oct 13 '22 22:10

Turtles Are Cute