4

分享一个Python不同时区时间转换的方法

 2 years ago
source link: https://vps.la/2021/10/03/%e5%88%86%e4%ba%ab%e4%b8%80%e4%b8%aapython%e4%b8%8d%e5%90%8c%e6%97%b6%e5%8c%ba%e6%97%b6%e9%97%b4%e8%bd%ac%e6%8d%a2%e7%9a%84%e6%96%b9%e6%b3%95/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
分享一个Python不同时区时间转换的方法 - VPS啦-VPS啦

分享一个Python不同时区时间转换的方法,主要有2中返回格式,一个是返回datetime格式,一个是返回str格式,需要请自行食用:

import datetime
import pytz
# src_timezone:原始时区
# dst_timezone:目标时区
# src_format:原始格式
# 返回datetime格式
def src2dst_time(src_timezone, dst_timezone, dst_time_str, src_format=’%Y-%m-%d %H:%M:%S’):
    est_tz = pytz.timezone(src_timezone) # 标注时间的时区
    local_tz = pytz.timezone(dst_timezone) # 北京时区
    # local_format = “%Y-%m-%d %H:%M:%S”  # 所需要的时间打印格式
    est_dt = datetime.datetime.strptime(dst_time_str, src_format)
    local_dt = est_dt.replace(tzinfo=est_tz).astimezone(local_tz) # 将原有时区换成我们需要的
    # time_str = local_dt.strftime(local_format)
    return local_dt
# src_timezone:原始时区
# dst_timezone:目标时区
# src_format:原始格式
# src_format:原始格式
# 返回格式化的str
def src2dst_str(src_timezone, dst_timezone, dst_time_str, src_format=’%Y-%m-%d %H:%M:%S’, dst_format=’%Y-%m-%d %H:%M:%S’):
    est_tz = pytz.timezone(src_timezone) # 标注时间的时区
    local_tz = pytz.timezone(dst_timezone) # 北京时区
    # dst_format = “%Y-%m-%d %H:%M:%S”  # 所需要的时间打印格式
    est_dt = datetime.datetime.strptime(dst_time_str, src_format)
    local_dt = est_dt.replace(tzinfo=est_tz).astimezone(local_tz) # 将原有时区换成我们需要的
    time_str = local_dt.strftime(dst_format)
    return time_str
time_datetime = src2dst_time(“Etc/GMT-3”, “Asia/Chongqing”, “2021-10-02 20:29:19”)
print(time_datetime)
print(type(time_datetime))
time_str = src2dst_str(“Etc/GMT-3”, “Asia/Chongqing”, “2021-10-02 20:29:19”, “%Y-%m-%d %H:%M:%S”, “%Y/%m/%d %H:%M:%S”)
print(time_str)
print(type(time_str))
# 执行结果:
# 2021-10-03 01:29:19+08:00
# <class ‘datetime.datetime’>
# 2021/10/03 01:29:19
# <class ‘str’>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK