基于时区的Python日期字符串操作 - DST

时间:2013-07-05 05:29:59

标签: python python-2.7 timezone

我的目标是将字符串(包含UTC日期和时间)作为输入,并根据时区差异将其转换为本地时区。我想出了以下代码

代码

import time
print "Timezone Diff", time.timezone/3600

def convertTime(string):
        print "Before Conversion"
        print "year",string[0:4],"month",string[5:7],"day",string[8:10]
        print "hour",string[11:13],"min",string[14:16]
        print "After Conversion"
        print "newhour",int(string[11:13])-(time.timezone/3600)
        newhour = int(string[11:13])-(time.timezone/3600) 
        if newhour>=24:
            print "year",string[0:4],"month",string[5:7],"newday",int(string[8:10])+1
            print "hour",newhour-24,"min",string[14:16]
convertTime('2013:07:04:14:00')

输出

Timezone Diff -10
Before Conversion
year 2013 month 07 day 04
hour 14 min 00
After Conversion
newhour 24
year 2013 month 07 newday 5
hour 0 min 00

此代码非常基本,显然不适用于月/年更改而不考虑闰年。任何人都可以建议我更好地解决这个问题。

3 个答案:

答案 0 :(得分:1)

以下是datetimepytz模块的解决方案,以我的时区为例:

import pytz
import datetime
s = '2013:07:04:14:00'
mydate = datetime.datetime.strptime(s, '%Y:%m:%d:%H:%M')
mydate = mydate.replace(tzinfo=timezone('Australia/Sydney'))
print mydate

打印:

2013-07-04 14:00:00+10:00

您可能需要“重塑”代码才能正常输出,但我希望这会有所帮助!

答案 1 :(得分:1)

要仅使用stdlib将UTC时间转换为本地时区,您可以使用中间时间戳值:

from datetime import datetime

def convertTime(timestring):
    utc_dt = datetime.strptime(timestring, '%Y:%m:%d:%H:%M')
    timestamp = (utc_dt - datetime.utcfromtimestamp(0)).total_seconds()
    return datetime.fromtimestamp(timestamp) # return datetime in local timezone

请参阅How to convert a python utc datetime to a local datetime using only python standard library?

要支持具有不同utc偏移的过去日期,您可能需要pytztzlocal个库(仅限stdlib解决方案在Ubuntu上工作正常;基于pytz的解决方案还应启用Windows支持):

from datetime import datetime

import pytz # $ pip install pytz
from tzlocal import get_localzone # $ pip install tzlocal

# get local timezone    
local_tz = get_localzone()

def convertTime(timestring):
    utc_dt = datetime.strptime(timestring, '%Y:%m:%d:%H:%M')
    # return naive datetime object in local timezone
    local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
    #NOTE: .normalize might be unnecessary
    return local_tz.normalize(local_dt).replace(tzinfo=None)

答案 2 :(得分:0)

下面的代码为我解决了这个问题。虽然pytz可能是最好的使用方法。但是如果你没有pytz,下面的解决方案可能是另一种选择。

import datetime

    def convertTime(timestring):
        UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()
        local_datetime = datetime.datetime.strptime(timestring, "%Y:%m:%d:%H:%M")
        result_utc_datetime = local_datetime - UTC_OFFSET_TIMEDELTA
        print result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S"),

    s = '2013:07:07:14:00'

    convertTime(s)