转换TZ格式

2024-05-19 02:50:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从API中读取一些信息,时间显示为:

2021-01-29T13:29:19.668Z

然而,我想将其理解为:

Jan 29, 2021 @ 1:29pm

有没有办法通过图书馆做到这一点?或者我必须自己创造一些东西


Tags: api信息图书馆时间jan办法
3条回答

我使用了datetime模块。 并使用split函数将日期与时间以及其他内容分开

import datetime

DT = "2021-01-29T13:29:19.668Z"

date,time = DT.split("T")

Year, Month, Day = date.split("-")

Hour, Minute, Seconds = time.split(":")

x = datetime.datetime( int(Year), int(Month), int(Day), int(Hour), int(Minute) )

x = x.strftime("%b %d, %Y @ %I:%M %p")

output = ''.join(( x[:-2], x[-2:].lower() ))

print(output)

您可能想探索pendulumpendulum是Python的datetime变得简单了

只需使用以下软件安装:

$ pip install pendulum

适用于您的案例的用法:

import pendulum

dt = pendulum.parse("2021-01-29T13:29:19.668Z")
print(dt.format("MMM DD, YYYY @ h:mm A"))

输出:

Jan 29, 2021 @ 1:29 PM

编辑:要获取EST中的时间(修改时间),只需执行以下操作:

import pendulum

dt = pendulum.parse("2021-01-29T13:29:19.668Z")
print(dt.in_tz("America/Toronto").format("MMM DD, YYYY @ h:mm A"))

输出:

Jan 29, 2021 @ 8:29 AM

但是,如果您不想修改输出,只想设置时区,请尝试以下操作:

dt = pendulum.parse("2021-01-29T13:29:19.668Z").set(tz="America/Toronto")
print(dt.timezone)
print(dt)
print(dt.format("MMM DD, YYYY @ h:mm A"))

输出:

Timezone('America/Toronto')
2021-01-29T13:29:19.668000-05:00
Jan 29, 2021 @ 1:29 PM
from datetime import datetime

string_time = "2021-01-29T13:29:19.668Z"

# see https://strftime.org/ for definitions of strftime directives
dt_format = "%Y-%m-%dT%H:%M:%S.%fZ"

output_format = "%b %d, %Y @ %-I:%-M%p" # the %p is uppercase AM or PM

output = datetime.strftime(datetime.strptime(string_time, dt_format), output_format)

# lower case the last 2 characters of output
# and join with all characters except the last 2
print(''.join((output[:-2], output[-2:].lower())))

输出:Jan 29, 2021 @ 1:29pm

相关问题 更多 >

    热门问题