【问题标题】:How can I calculate new time zone in python?如何在 python 中计算新时区?
【发布时间】:2011-03-03 04:14:04
【问题描述】:

假设我的时间是 04:05,时区是 -0100(格林威治标准时间)

我想计算新的时间,即 03:05

python中是否有任何函数可以进行计算?

谢谢

【问题讨论】:

    标签: python datetime time timezone gmt


    【解决方案1】:

    您可以使用“pytz”来完成此操作。尝试:

    from string import atoi
    from datetime import datetime
    import pytz # Available http://sourceforge.net/project/showfiles.php?group_id=79122
    
    thedate = "20080518"
    thetime = "2210"
    
    europe_tz = pytz.timezone('Europe/Paris') # Note that your local install timezone should be settings.py
    brazil_tz = pytz.timezone('America/Sao_Paulo')
    server_tz = pytz.timezone('America/Los_Angeles')
    
    stat_time = datetime(atoi(thedate[0:4]), atoi(thedate[4:6]), atoi(thedate[6:8]), atoi(thetime[0:2]), atoi(thetime[2:4]), 0, tzinfo=europe_tz)
    
    stat_time.astimezone(brazil_tz) # returns time for brazil
    stat_time.astimezone(server_tz) # returns server time
    

    来源:http://menendez.com/blog/python-timezone-conversion-example-using-pytz/

    【讨论】:

    • 它对我不好,我有 2 个字符串——“04:05”和“-0100”,我想用它们来计算新时间,但是 10 倍!!
    【解决方案2】:

    试试这样的:

       >>> import datetime
       >>> my_time = datetime.datetime.strptime('04:05', '%H:%M')
       >>> my_time
       datetime.datetime(1900, 1, 1, 4, 5)
       >>> offset_str = '-0100'
       >>> offset = datetime.timedelta(hours=int(offset_str.lstrip('-')[:2]), minutes=int(offset_str.lstrip('-')[2:])) * (-1 if offset_str.startswith('-') else 1)
       >>> offset 
       datetime.timedelta(-1, 82800)
       >>> my_time + offset
       datetime.datetime(1900, 1, 1, 3, 5)
       >>> (my_time + offset).time()
       datetime.time(3, 5)
    

    简而言之:

       >>> import datetime
       >>> my_time = datetime.datetime.strptime('04:05', '%H:%M')
       >>> offset_str = '-0100'
       >>> offset = datetime.timedelta(hours=int(offset_str.lstrip('-')[:2]), minutes=int(offset_str.lstrip('-')[2:])) * (-1 if offset_str.startswith('-') else 1)
       >>> (my_time + offset).time()
       datetime.time(3, 5)
    

    【讨论】:

    • 10 倍!这样就可以了,但是任何人都可以想到一种更蟒蛇的方式吗?
    猜你喜欢
    • 2014-07-12
    • 2019-11-04
    • 2019-09-15
    • 1970-01-01
    • 2020-01-12
    • 2017-02-01
    • 2017-10-12
    • 2018-04-19
    • 1970-01-01
    相关资源
    最近更新 更多