本地时间与UTC时间的转换、处理一直困扰了很长时间,直到在别人的一篇博客中学到了很多,特此记录下来。
摘自:http://blog.sina.com.cn/s/blog_4da051a60102v221.html
一、上面博客中的内容
1 import time 2 import datetime 3 4 5 def utc2local(utc_st): 6 """UTC时间转本地时间(+8:00)""" 7 now_stamp = time.time() 8 local_time = datetime.datetime.fromtimestamp(now_stamp) 9 utc_time = datetime.datetime.utcfromtimestamp(now_stamp) 10 offset = local_time - utc_time 11 local_st = utc_st + offset 12 return local_st 13 14 def local2utc(local_st): 15 """本地时间转UTC时间(-8:00)""" 16 time_struct = time.mktime(local_st.timetuple()) 17 utc_st = datetime.datetime.utcfromtimestamp(time_struct) 18 return utc_st 19 20 utc_time = datetime.datetime(2014, 9, 18, 10, 42, 16, 126000) 21 22 # utc转本地 23 local_time = utc2local(utc_time) 24 print local_time.strftime("%Y-%m-%d %H:%M:%S") 25 # output:2014-09-18 18:42:16 26 27 28 # 本地转utc 29 utc_tran = local2utc(local_time) 30 print utc_tran.strftime("%Y-%m-%d %H:%M:%S") 31 # output:2014-09-18 10:42:16
二、字符串时间的处理
将字符串类型的utc时间转换为本地时间(字符串类型)
1 # -*- coding:utf-8 -*- 2 3 import time 4 import datetime 5 6 7 # 将时间类型转换为一定格式的字符串 8 def time_to_string_ms(time_obj): 9 t_str = time_obj.strftime('%Y-%m-%dT') 10 t_str = t_str + time_obj.strftime('%H:%M:%S.') 11 t_str = t_str+(time_obj.strftime('%f'))[0:3] 12 return t_str 13 14 15 # utc字符串时间->本地字符串时间 16 def utc2local_str(utc_str): 17 td = datetime.datetime.strptime(utc_str, '%Y-%m-%dT%H:%M:%S.%f') 18 19 # 计算本地与UTC的时差 20 now_stamp = time.time() 21 local_time = datetime.datetime.fromtimestamp(now_stamp) 22 utc_time = datetime.datetime.utcfromtimestamp(now_stamp) 23 offset = local_time - utc_time 24 25 td += offset 26 return time_to_string_ms(td) 27 28 29 # utc字符串:'2018-01-21 09:00:00.123456' 30 time_now_utc = datetime.datetime.utcnow() 31 print time_now_utc 32 utc_s = time_to_string_ms(time_now_utc) 33 print utc_s 34 # 本地时间字符串 35 local_s = utc2local_str(utc_s)