python - 在Python中将UTC字符串转换为本地日期时间字符串?

标签 python datetime

我没有时区的名称,只有一个偏移值,例如 +0400 .

我有 UTC 格式的日期时间字符串:如 2014-01-07T09:29:35Z .

我想要一个本地时间的字符串,例如 2014-01-07T13:29:35 .

如何做到这一点?

最佳答案

您可以编写一个函数来转换字符串格式。

from datetime import datetime, timedelta
old_time = '2014-01-07T09:29:35Z'

def time_converter(old_time, time_zone):
    time_zone = float(time_zone[:3] + ('.5' if time_zone[3] == '3' else '.0'))
    str_time = datetime.strptime(old_time, "%Y-%m-%dT%H:%M:%SZ")
    return (str_time + timedelta(hours=time_zone)).strftime("%Y-%m-%dT%H:%M:%SZ")

if __name__ == '__main__':
    for time_zone in ('+0400', '+0430', '-1400'):
        print(time_converter(old_time, time_zone))

输出:

2014-01-07T13:29:35Z
2014-01-07T13:59:35Z
2014-01-06T19:29:35Z

关于python - 在Python中将UTC字符串转换为本地日期时间字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21154971/

相关文章:

C# - 获取两个日期之间的天数

android - 时间跨度 至 UTC 毫秒

c# - C# .NET 中的模糊日期时间选择器控件?

python - 如何在 python 中使用@..以及@property 和@classmethod

python - 如何每五分钟下载一个网页?

python - 在开发中提供静态文件

ios - 将 iOS 本地时区转换为已知时区

datetime - Hive 时间戳 ISO 到 UTC 的转换

Python - 从旋转角度对 OpenCV 进行透视变换

python - Py2exe 添加包(例如 Carbon)到 exe