Python带时区日期与UTC时间互转

    通过正则匹配带时区格式字符串进行格式校验后转换为时间类型

    使用datime类型的astimezone方法获得不同时区的时间字符串

import re
from datetime import datetime


def format_datestr_with_zone(datetime_str: str):
    """
    格式化带时区时间字符串,返回datetime类型时间
    :param datetime_str: 2022-06-14T15:16:31+00:00
    :return: datetime
    """
    format_ = '%Y-%m-%d %H:%M:%S'
    if '.' in datetime_str:
        format_ = format_ + '.%f'
    zone_ = re.search(r'[+-]\d{2}:\d{2}', datetime_str)
    if zone_:
        format_ = format_ + '%z'
    if 'T' in datetime_str:
        format_ = format_.replace(' ', 'T')
    return datetime.strptime(datetime_str, format_)


print(format_datestr_with_zone('2022-06-14T15:19:39'))
# datetime.datetime(2022, 6, 14, 15, 19, 39)

print(format_datestr_with_zone('2022-06-14T15:19:39.000+00:00'))
# datetime.datetime(2022, 6, 14, 15, 19, 39, tzinfo=datetime.timezone.utc)

print(format_datestr_with_zone('2022-06-14T15:19:39.000+08:00'))
# datetime.datetime(2022, 6, 14, 15, 19, 39, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800)))

# 转换为本地时区的时间
print(format_datestr_with_zone('2022-06-14T15:19:39.000+00:00').astimezone())
# datetime.datetime(2022, 6, 14, 23, 19, 39, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), '中国标准时间'))

# 转换为UTC时间
print(format_datestr_with_zone('2022-06-14T15:19:39+08:00').astimezone(pytz.UTC))
# datetime.datetime(2022, 6, 14, 7, 19, 39, tzinfo=<UTC>)


print(datetime.now())
# datetime.datetime(2022, 6, 14, 11, 16, 28, 45080)
print(datetime.now(pytz.UTC))
# datetime.datetime(2022, 6, 14, 3, 16, 29, 282739, tzinfo=<UTC>)

# 时区转换
print(format_datestr_with_zone('2022-06-14T15:19:39.000+05:00'))
# datetime.datetime(2022, 6, 14, 15, 19, 39, tzinfo=datetime.timezone(datetime.timedelta(seconds=18000)))

print(format_datestr_with_zone('2022-06-14T15:19:39.000+05:00').astimezone())
# datetime.datetime(2022, 6, 14, 18, 19, 39, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), '中国标准时间'))

print(format_datestr_with_zone('2022-06-14T15:19:39.000+05:00').astimezone(pytz.UTC))
# datetime.datetime(2022, 6, 14, 10, 19, 39, tzinfo=<UTC>)

时间戳转时间,可指定时区

from datetime import datetime
import pytz


datetime.fromtimestamp(1654828314).strftime("%Y-%m-%d %H:%M:%S")
# '2022-06-10 10:31:54'
datetime.fromtimestamp(1654828314, pytz.utc).strftime("%Y-%m-%d %H:%M:%S")
# '2022-06-10 02:31:54'

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Amour_柒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值