I have a UTC time string like so
supplied_datetime = 20160711230000 -0500
This is the format
yyyyMMddhhmmss +/-hhmm
Now if I take that offset (-5hrs) from the original time it should read
supplied_datetime = 20160711180000
The next part is that I need to correct based on the local time making sure to account for any dst times.
So lets say i'm in the UK which is UTC 0000 but we are in DST +0100, then the time that ultimately gets displayed to the user will be
supplied_datetime = 20160711190000
So the formula is supplied_datetime - (supplied_utc_offset + local_utc_offset)
This is as far as I have got before asking here.
local_utc_offset = calendar.timegm(time.localtime()) - calendar.timegm(time.gmtime(time.mktime(time.localtime())))
supplied_utc_offset = parse(programme.get('start')[:20])
答案 0 :(得分:0)
If the format of your date time strings are always consistent, you can manually obtain the local datetime given the utc datetime.
time.timezone
gives local offset in seconds.
Then you just need to parse the datetime string and add it with local offset in hours as well as the offset in the datetime string:
from datetime import datetime
import time
dst = time.localtime().tm_isdst # daylight saving
local_offset = (dst-(time.timezone / 3600)) * 10000 # Local offset in hours format
strtime = '20160711230000 -0500' # The original datetime string
dtstr, offset = strtime[:-6], strtime[-5:] # separate the offset from the datetime string
utc_dt = datetime.strptime(dtstr, '%Y%m%d%H%M%S')
local_dtstr = str(int(dtstr) + int(offset) * 100 + local_offset) # get local time string
local_dt = datetime.strptime(local_dtstr, '%Y%m%d%H%M%S')
In [37]: utc_dt
Out[37]: datetime.datetime(2016, 7, 11, 23, 0)
In [38]: local_dt
Out[38]: datetime.datetime(2016, 7, 11, 19, 0)
答案 1 :(得分:0)
在@CentAu的帮助下,我设法回答如下
import time
import calendar
from datetime import datetime, timedelta
def datetime_from_utc_to_local(input_datetime):
#Get local offset from UTC in seconds
local_offset_in_seconds = calendar.timegm(time.localtime()) - calendar.timegm(time.gmtime(time.mktime(time.localtime())))
#split time from offset
input_datetime_only, input_offset_only = input_datetime[:-6], input_datetime[-5:]
#Convert input date to a proper date
input_datetime_only_dt = datetime.strptime(input_datetime_only, '%Y%m%d%H%M%S')
#Convert input_offset_only to seconds
input_offset_mins, input_offset_hours = int(input_offset_only[3:]), int(input_offset_only[:-2])
input_offset_in_total_seconds = (input_offset_hours * 60 * 60) + (input_offset_mins * 60);
#Get the true offset taking into account local offset
true_offset_in_seconds = local_offset_in_seconds + input_offset_in_total_seconds
# add the true_offset to input_datetime
local_dt = input_datetime_only_dt + timedelta(seconds=true_offset_in_seconds)
return str(input_datetime) + ' ' + str(local_dt)
t = datetime_from_utc_to_local("20160711230000 +0300")
print (t)