【问题标题】:Converting TZ Format转换 TZ 格式
【发布时间】:2021-02-07 20:01:47
【问题描述】:

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

2021-01-29T13:29:19.668Z

但是,我希望将其解读为:

Jan 29, 2021 @ 1:29pm

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

【问题讨论】:

标签: python date datetime time


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    您可能想探索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
    

    【讨论】:

    • 这是完美的。又是一个轻微的扭曲。如果这是 GMT 0 时间。我将如何将其更改为 EST 时间? (-5 小时)
    • 我可以使用:dt = dt.subtract(hours=5)
    • 一件小事。 3:00 PM 显示为 3:PM 我通过以下方式修复了此问题:从:print(dt.format("MMM DD, YYYY @ h:m A")) 到:print(dt.format("MMM DD, YYYY @ h:mm A"))
    【解决方案3】:

    我使用了日期时间模块。 并使用 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 2016-05-24
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 2020-05-01
      • 2016-08-26
      相关资源
      最近更新 更多