Python datetime.now() with timezone

17,620

Solution 1

If you are using Python 3.2 or newer, you need to create a datetime.timezone() object; it takes an offset as a datetime.timedelta():

from datetime import datetime, timezone, timedelta

timezone_offset = -8.0  # Pacific Standard Time (UTC−08:00)
tzinfo = timezone(timedelta(hours=timezone_offset))
datetime.now(tzinfo)

For earlier Python versions, it'll be easiest to use an external library to define a timezone object for you.

The dateutil library includes objects to take a numerical offset to create a timezone object:

from dateutil.tz import tzoffset

timezone_offset = -8.0  # Pacific Standard Time (UTC−08:00)
tzinfo = tzoffset(None, timezone_offset * 3600)  # offset in seconds
datetime.now(tzinfo)

Solution 2

I suggest you to use pytz, as it could be simpler.

According to the description:

This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference

>>> from datetime import datetime
>>> import pytz

>>> datetime.now(tz=pytz.UTC)
datetime.datetime(2021, 11, 12, 20, 59, 54, 579812, tzinfo=<UTC>)

>>> datetime.now(tz=pytz.timezone("Europe/Oslo"))
datetime.datetime(2021, 11, 12, 22, 0, 4, 911480, tzinfo=<DstTzInfo 'Europe/Oslo' CET+1:00:00 STD>)

>>> [tz for tz in pytz.common_timezones if tz.startswith("US")]
['US/Alaska',
 'US/Arizona',
 'US/Central',
 'US/Eastern',
 'US/Hawaii',
 'US/Mountain',
 'US/Pacific']
 

Share:
17,620
l0gg3r
Author by

l0gg3r

Author and maintainer of https://github.com/l0gg3r/LGBluetooth

Updated on June 07, 2022

Comments

  • l0gg3r
    l0gg3r about 2 years

    I have a timezone which is float (for example 4.0).
    I want to construct datetime with given timezone.

    I tried this,

    datetime.now(timezone)
    

    but it throws

    TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'float'
    

    So I wonder how can I make tzinfo from float?

    • NDevox
      NDevox about 9 years
      I'm assuming your float is +- hours from gmt?
    • Matt Johnson-Pint
      Matt Johnson-Pint about 9 years
      Please read "Time Zone != Offset" in the timezone tag wiki.
  • Martijn Pieters
    Martijn Pieters over 3 years
    @jcady: note that the variable name timezone was supposed to be the float value the OP was using, and still used in the second code example..