Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the utcoffset method do in datetime - Python

I know this questions answer is usually "go to Python's documentation". I have read it and am still not a 100% sure what the uctcoffset method does.

I assume that it takes the timezone - utc and gives the difference but I need to be 100% sure.

like image 218
Curious Lambda Avatar asked Nov 19 '16 16:11

Curious Lambda


2 Answers

yes, it is doing exactly what you think it does. Here are the official docs.

Edit: To be precise, it does not take a timezone, it takes 0 paramters. You invoke it on a datimeobject, that object has a timezone associated to it, if it is timezone aware. In that case the method wil return a timedelta object, which represents the differenc between the timezone of the datetime object and utc

like image 25
zabeltech Avatar answered Oct 21 '22 01:10

zabeltech


The utcoffset method of a datetime gives you the difference between the "wall clock" time of the datetime and the "wall clock" time of the same point in time in UTC, so, exactly as you expect (dt - dt_as_utc). The reason it is a function is that for many time zones (such as those with daylight savings), the offset changes over the course of a year. As an example:

from datetime import datetime, timedelta
from dateutil import tz

NYC = tz.gettz('America/New_York')  # Note: ambiguous time support
                                    # requires version >= 2.6.0, be aware.

dt1 = datetime(2015, 5, 21, 12, 0, tzinfo=NYC)    # EST
dt2 = datetime(2015, 12, 21, 12, 0, tzinfo=NYC)   # EDT

print(dt1.utcoffset() / timedelta(hours=1))
# -4
print(dt1.tzname())
# EDT


print(dt2.utcoffset() / timedelta(hours=1))
# -5
print(dt2.tzname())
# EST

As you can see, the same applies to the tzname() function. For naive datetimes (those with no datetime), utcoffset() and tzname() should both return None.

As a note, I would generally advise not using this function to calculate a UTC timestamp, rather, you should use astimezone() with either dateutil.tz.tzutc or pytz.UTC or, if you are using Python version >= 3.2, you can use the datetime.timezone.utc object.

like image 78
Paul Avatar answered Oct 21 '22 03:10

Paul