How do I use timezones with a datetime object in p

2019-01-10 20:25发布

How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()

import datetime, re
from datetime import tzinfo

class myTimeZone(tzinfo):
    """docstring for myTimeZone"""
    def utfoffset(self, dt):
        return timedelta(hours=1)

def myDateHandler(aDateString):
    """u'Sat,  6 Sep 2008 21:16:33 EDT'"""
    _my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)')
    day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups()
    month = [
            'JAN', 'FEB', 'MAR', 
            'APR', 'MAY', 'JUN', 
            'JUL', 'AUG', 'SEP', 
            'OCT', 'NOV', 'DEC'
    ].index(month.upper()) + 1
    dt = datetime.datetime(
        int(year), int(month), int(day), 
        int(hour), int(minute), int(second)
    )                   
    # dt = dt - datetime.timedelta(hours=1)
    # dt = dt - dt.tzinfo.utfoffset(myTimeZone())
    return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0)

def main():
    print myDateHandler("Sat,  6 Sep 2008 21:16:33 EDT")

if __name__ == '__main__':
    main()

4条回答
Animai°情兽
2楼-- · 2019-01-10 20:49

I recommend babel and pytz when working with timezones. Keep your internal datetime objects naive and in UTC and convert to your timezone for formatting only. The reason why you probably want naive objects (objects without timezone information) is that many libraries and database adapters have no idea about timezones.

查看更多
淡お忘
3楼-- · 2019-01-10 20:57

The Python standard library doesn't contain timezone information, because unfortunately timezone data changes a lot faster than Python. You need a third-party module for this; the usual choice is pytz

查看更多
唯我独甜
4楼-- · 2019-01-10 21:04

For the current local timezone, you can you use:

>>> import time
>>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
>>> offset / 60 / 60 * -1
-9

The value returned is in seconds West of UTC (with areas East of UTC getting a negative value). This is the opposite to how we'd actually like it, hence the * -1.

localtime().tm_isdst will be zero if daylight savings is currently not in effect (although this may not be correct if an area has recently changed their daylight savings law).

查看更多
狗以群分
5楼-- · 2019-01-10 21:04

We are familiar to timezone cut off from GMT (now UTC), but Python takes timezone cut off from Western. That's why there are negative timezone cutoff's in Python, I believe.

查看更多
登录 后发表回答