Python - Setting a datetime in a specific timezone (without UTC conversions)

前端 未结 2 541
不思量自难忘°
不思量自难忘° 2020-12-31 00:23

Just to be clear, this is python 2.6, I am using pytz.

This is for an application that only deals with US timezones, I need to be able to anchor a date (today), and

相关标签:
2条回答
  • 2020-12-31 00:29

    There are at least two issues:

    1. you shouldn't pass a timezone with non-fixed UTC offset such as "US/Pacific" as tzinfo parameter directly. You should use pytz.timezone("US/Pacific").localize() method instead
    2. .strftime('%s') is not portable, it ignores tzinfo, and it always uses the local timezone. Use datetime.timestamp() or its analogs on older Python versions instead.

    To make a timezone-aware datetime in the given timezone:

    #!/usr/bin/env python
    from datetime import datetime 
    import pytz # $ pip install pytz
    
    tz = pytz.timezone("US/Pacific")
    aware = tz.localize(datetime(2011, 2, 11, 20), is_dst=None)
    

    To get POSIX timestamp:

    timestamp = (aware - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
    

    (On Python 2.6, see totimestamp() function on how to emulate .total_seconds() method).

    0 讨论(0)
  • 2020-12-31 00:39

    Create a tzinfo object utc for the UTC time zone, then try this:

    #XXX: WRONG (for any timezone with a non-fixed utc offset), DON'T DO IT
    datetime(2011,2,11,20,0,0,0,pacific).astimezone(utc).strftime("%s")
    

    Edit: As pointed out in the comments, putting the timezone into the datetime constructor isn't always robust. The preferred method using the pytz documentation would be:

    pacific.localize(datetime(2011,2,11,20,0,0,0)).astimezone(utc).strftime("%s")
    

    Also note from the comments that strftime("%s") isn't reliable, it ignores the time zone information (even UTC) and assumes the time zone of the system it's running on. It relies on an underlying C library implementation and doesn't work at all on some systems (e.g. Windows).

    0 讨论(0)
提交回复
热议问题