【问题标题】:How to convert local time into GMT time zone in Python如何在 Python 中将本地时间转换为 GMT 时区
【发布时间】:2021-03-12 07:56:50
【问题描述】:

输入:

datetime.now().time()

这次我需要在 python 中转换成 GMT 格式

谁能帮我解决这个问题?

【问题讨论】:

  • 什么是 GMT 格式? UTC 通常是 GMT...
  • @MrFuppes 像现在的 IST 时间需要转换成 (GMT+05:30) 格式

标签: python-3.x datetime gmt


【解决方案1】:

假设“转换”是指格式为带有特定后缀的字符串。

选项 1:本地化到您机器的时区和 strftime:

from datetime import datetime

datetime.now().astimezone(None).strftime("%Y-%m-%d %H:%M:%S GMT%z")
# I'm on CET so this gives me
# '2020-11-30 13:43:15 GMT+0100'

选项 2:本地化到特定时区 - 和 stftime:

# Python 3.9: from zoneinfo import ZoneInfo
from dateutil.tz import gettz # Python <3.9

datetime.now(gettz("Asia/Kolkata")).strftime("%Y-%m-%d %H:%M:%S GMT%z")
# '2020-11-30 18:14:54 GMT+0530'

【讨论】:

  • 我需要像这样传递 GMT+5:30 或 GMT-5:00 这样的参数,而不是 GMT%z,这可能吗?
  • @AswathyMA:不确定我理解你真正想要做什么。是否要将日期时间从一个时区转换为另一个时区?
  • @MrFuppes:是的...例如:我想将 IST 时间转换为 (GMT+5:30) 格式。
猜你喜欢
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
  • 2013-10-29
  • 2012-08-28
  • 2011-01-04
  • 1970-01-01
相关资源
最近更新 更多