Calculating time differences given daylight savings time

Chris “Kwpolska” Warrick kwpolska at gmail.com
Thu Apr 3 09:46:50 EDT 2014


On Thu, Apr 3, 2014 at 3:45 AM, Washington Ratso <jobhunts02 at aol.com> wrote:
> I am running Python 2.7 and would like to be able to calculate to the second the time difference between now and some future date/time in the same timezone while taking into account daylight savings time.  I do not have pytz.  Any ideas how to do it?
>
> If it requires having pytz, how would I do it with pytz?
>
> Thank you.
> --
> https://mail.python.org/mailman/listinfo/python-list

It requires having pytz, or dateutil, in order to get timezone
objects*.  You can also create those objects yourself, but that’s
tricky — and you SHOULD NOT do time zones on your own and just use
something else.  Why?  See [0].

Example with pytz:

# Necessary imports
import pytz
from datetime import datetime

# the timezone in this example is Europe/Warsaw — use your favorite one
tz = pytz.timezone('Europe/Warsaw')

now = datetime.now(tz)
# Note I’m not using the tzinfo= argument of datetime(), it’s flaky
and seemingly uses a historic WMT (+01:24) timezone that is dead since
1915.
future = tz.localize(datetime(2014, 12, 24))

# And now you can happily do:

delta = future - now

# and you will get the usual timedelta object, which you can use the usual way.


###

* pytz ships the Olson tz database, while dateutil maps uses your
system’s copy of the tz database (if you are on Linux, OS X or
anything else that is not Windows, really) or maps to the Windows
registry.  Use whichever suits you.

[0]: http://www.youtube.com/watch?v=-5wpm-gesOY

-- 
Chris “Kwpolska” Warrick <http://kwpolska.tk>
PGP: 5EAAEA16
stop html mail | always bottom-post | only UTF-8 makes sense



More information about the Python-list mailing list