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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With