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.
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 favoriteone
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]: