如何在python中使用datetime对象的时区? [英] How do I use timezones with a datetime object in python?

查看:142
本文介绍了如何在python中使用datetime对象的时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的时区如何正确表示不同的时区?以下示例仅仅是因为我知道EDT比我早一个小时,所以我可以取消对myTimeZone()的减法。

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


推荐答案

在使用时区时,我推荐 babel pytz 保持内部datetime对象天真和UTC,并转换为您的时区仅格式。你可能想要天真的对象(没有时区信息的对象)的原因是许多库和数据库适配器不知道时区。

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.


  • < a href =http://babel.pocoo.org/ =noreferrer> Babel

  • pytz

  • Babel
  • pytz

这篇关于如何在python中使用datetime对象的时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆