python - Python 将原始 GMT 转换为其他时区,例如 SGT
问题描述
我正在尝试从 GMT 转换为例如 SGT:
例如,值
格林威治标准时间 0348 应该是上午 11:48 格林威治标准时间 1059 应该是下午 6:59
我该怎么做呢?
我努力了:
date="03:48"
curr = (
dt.datetime.strptime(date, "%H:%M")
.astimezone(timezone('Asia/Singapore'))
)
print(curr)
但我收到 OSError: [Errno 22] Invalid argument
解决方案
假设您有一个代表 UTC的天真日期时间对象:
from datetime import datetime, timezone
from dateutil import tz
now = datetime.now()
print(repr(now))
>>> datetime.datetime(2020, 7, 28, 8, 5, 42, 553781)
确保使用replacetzinfo
将属性设置为 UTC :
now_utc_aware = now.replace(tzinfo=timezone.utc)
print(repr(now_utc_aware))
>>> datetime.datetime(2020, 7, 28, 8, 5, 42, 553781, tzinfo=datetime.timezone.utc)
现在您可以使用astimezone转换到另一个时区:
now_sgt = now_utc_aware.astimezone(tz.gettz('Asia/Singapore'))
print(repr(now_sgt))
>>> datetime.datetime(2020, 7, 28, 16, 5, 42, 553781, tzinfo=tzfile('Singapore'))
旁注,参考您的其他问题,如果您正确解析,您已经获得了一个知道的日期时间对象:
date = "2020-07-27T16:38:20Z"
dtobj = datetime.fromisoformat(date.replace('Z', '+00:00'))
print(repr(dtobj))
>>> datetime.datetime(2020, 7, 27, 16, 38, 20, tzinfo=datetime.timezone.utc)
推荐阅读
- sql - PostgreSQL:使用视图和触发器在多个表中插入元组
- python - 如何从 regex.split() 获得正确的输出?
- angular - Ionic 3 AdMob 错误:Object(...) 不是函数
- ruby-on-rails - Rails 中的命名空间表单对象
- c# - CAS 政策 - 无法打开表单设计器
- php - 语法错误,意外 '=>' (T_DOUBLE_ARROW),期待 ')' (查看:C:\xampp\htdocs\login\resources\views\pages\index.blade.php)
- asp.net - 如果我在模型上生成构造函数,是否需要生成新的迁移?
- python - 在 kmeans Lloyds 算法中计算距离
- android - Timertask Run() 方法不能工作更长的时间,比如 2 小时
- javascript - javascript push 导致 main 函数参数用于确认使用