Search code examples
pythonpython-2.7datetimetimezone

Python datetime.now() with timezone


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?


Solution

  • 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)