python解决格式化时间转成时间戳涉及时区问题

1.格式化时间转时间戳方法:


TIME_ZONE = 'Asia/Shanghai'

def convert2ms(timestamp):
    if isinstance(timestamp, str):
        timestamp = int(timestamp)
    return int(timestamp * 1000)

def get_timestamp_by_datetime(dt):
    try:
        tz = pytz.timezone(TIME_ZONE)
        t = tz.localize(dt)
        t = t.astimezone(pytz.utc)
        ts = int(time.mktime(t.utctimetuple())) - time.timezone
        return convert2ms(ts)
    except Exception as e:
        return 0


def str2datetime(dt_str, formatter="%Y%m%d%H%M%S"):
    return datetime.datetime.strptime(dt_str, formatter)

time_st = "20201214091003"
dt = str2datetime(time_st)
time_ = get_timestamp_by_datetime(dt)
print(time_)
结果:
1607908203000

2.时间戳转换为格式化时间:

TIME_ZONE = 'Asia/Shanghai'
def convert2second(timestamp):
    if isinstance(timestamp, str):
        timestamp = int(timestamp)
    return int(timestamp / 1000)

def datetime2str(dt, formatter="%Y%m%d%H%M%S"):
    return dt.strftime(formatter)

def get_datetime_by_ts(timestamp):
    if len(str(timestamp)) == 13:
        timestamp = convert2second(timestamp)

    tz = pytz.timezone(TIME_ZONE)
    dt = pytz.datetime.datetime.fromtimestamp(timestamp, tz)
    return dt


def get_str_by_ts(timestamp, formatter="%Y-%m-%d %H:%M:%S"):
    dt = get_datetime_by_ts(timestamp)
    return datetime2str(dt, formatter)

time_ = get_str_by_ts('1607908203000')
print(time_)
结果:
2020-12-14 09:10:03

猜你喜欢

转载自blog.csdn.net/weixin_43697214/article/details/111173192