Django报错:MySQL ...USE_TZ is False pythonUTC格式与本地互转
故障
今天django从第三方接口获取到字段时间,然后插入mysql的时候报如下错:
ValueError: MySQL backend does not support timezone-aware datetimes when USE_TZ is False.
原因
这是因为在 setting 中我们有如下配置
USE_TZ = False
解决方法:
获取到的 时间用下面的函数 转换下。
def utc2local_format(utc_string): UTC_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" utcTime = datetime.datetime.strptime(utc_string, UTC_FORMAT) localTime = utcTime + datetime.timedelta(hours=8) # 上海时区 加 8 小时 return localTime
以下摘自网络
两种时间格式
UTC时间格式:2014-09-18T10:42:16.126Z
普通时间格式:2014-09-18 10:42:16.126
>>> import datetime >>> utc = "2014-09-18T10:42:16.126Z" >>> local = "2014-09-18 10:42:16" >>> UTC_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" >>> LOCAL_FORMAT = "%Y-%m-%d %H:%M:%S" >>> datetime.datetime.strptime(utc, UTC_FORMAT) datetime.datetime(2014, 9, 18, 10, 42, 16, 126000) >>> datetime.datetime.strptime(local, LOCAL_FORMAT) datetime.datetime(2014, 9, 18, 10, 42, 16)
转换通用函数
import time import datetime def utc2local(utc_st): ''' UTC时间转本地时间) ''' now_stamp = time.time() local_time = datetime.datetime.fromtimestamp(now_stamp) utc_time = datetime.datetime.utcfromtimestamp(now_stamp) offset = local_time - utc_time local_st = utc_st + offset return local_st def local2utc(local_st): ''' 本地时间转UTC时间 ''' time_struct = time.mktime(local_st.timetuple()) utc_st = datetime.datetime.utcfromtimestamp(time_struct) return utc_st
使用举例
utc_time = datetime.datetime(2014, 9, 18, 10, 42, 16, 126000) # utc转本地 local_time = utc2local(utc_time) print local_time.strftime("%Y-%m-%d %H:%M:%S") # output:2014-09-18 18:42:16 # 本地转utc utc_tran = local2utc(local_time) print utc_tran.strftime("%Y-%m-%d %H:%M:%S") # output:2014-09-18 10:42:16
0顶
0 踩
共 0 条评论