記得導入需要的包例如:
import datetime
import time
1.utc時間轉化爲當地時間(cst時間)
def utc2local(utc_date):
now_stamp = time.time()
local_time = datetime.datetime.fromtimestamp(now_stamp)
utc_time = datetime.datetime.utcfromtimestamp(now_stamp)
offset = local_time - utc_time
res_time = utc_date + offset
return res_time
2.當地時間轉化爲utc時間
def local2utc(local_date):
now_stamp = time.time()
local_time = datetime.datetime.fromtimestamp(now_stamp)
utc_time = datetime.datetime.utcfromtimestamp(now_stamp)
offset = local_time - utc_time
res_time = local_date - offset
return res_time
3.字符串轉換時間
##such as format = "%Y-%m-%dT%H:%M:%SZ"
def string2datetime(str,format="%Y-%m-%dT%H:%M:%SZ"):
return datetime.datetime.strptime(str,format)
4.datetime轉字符串
## such as format = "%Y-%m-%dT%H:%M:%SZ"
def datetime2str(date_time,format="%Y-%m-%dT%H:%M:%SZ"):
return date_time.strftime(format)
5.字符串轉化timestamp
##format = "%Y-%m-%dT%H:%M:%S+0000"
def str2timestamp(str,format="%Y-%m-%dT%H:%M:%S+0000"):
struct_time = time.strptime(utc_str,format)
timestamp = time.mktime(struct_time)
return timestamp
6.timestamp轉化爲date
def timestamp2date(now_stamp):
return datetime.datetime.fromtimestamp(now_stamp)
7.獲取當前時間點 ,並自動格式化
def get_time_now_in_cst(format="%Y-%m-%d %H:%M:%S"):
tz = pytz.timezone('Asia/Shanghai')
return datetime.datetime.now(tz).strftime(format)