【问题标题】:Using Python3's datetime to format a date-time as per server's response's format [duplicate]使用 Python3 的日期时间根据服务器的响应格式格式化日期时间 [重复]
【发布时间】:2021-12-12 15:56:37
【问题描述】:
>>> mtime
1634725796.7212281
>>> from datetime import datetime
>>> datetime.fromtimestamp(mtime)
datetime.datetime(2021, 10, 20, 15, 59, 56, 721228)
>>>

我希望准确返回格式为 Date: Wed, 20 Oct 2021 15:59:56 GMT 的日期时间字符串,这是上次修改页面时服务器发送的格式。

https://serverfault.com/questions/168345/sending-content-message-body-along-with-304-not-modified-header

【问题讨论】:

标签: python-3.x datetime


【解决方案1】:

您需要使用datetime.strftime 函数来格式化日期时间。

如果您的日期时间没有时区:

>>> from datetime import datetime

>>> FORMAT_STR = "Date: %a, %d %b %Y %H:%M:%S"

>>> example_time = datetime(2021, 10, 20, 15, 59, 56, 721228)

>>> formatted_time = example_time.strftime(FORMAT_STR)

>>> print(formatted_time)
Date: Wed, 20 Oct 2021 15:59:56 

如果您的日期时间对象可以识别时区:

使用%Z 格式选项获取格式字符串中的时区。

【讨论】:

  • 这是有风险的,您完全忽略了日期时间是否实际上是 GMT(或时区感知)。
  • 这更直接:from email.utils import formatdate; print(formatdate(mtime, usegmt=True))
  • @jonrsharpe 这是真的,但时区信息不能从时间戳中获得。这取决于系统,需要从操作系统中获取。
  • 根据定义,时间戳 is 采用 UTC。但我的观点是,您的回答显示了一个幼稚的日期时间,它将是 local,并且只是在最后打了一个可能不正确的“GMT”。例如,上面 MrFuppes 的评论显示了如何根据时间戳创建感知日期时间。
  • @jonrsharpe 我本人对硬编码的 GMT 持怀疑态度。我已经更新了我的答案。
猜你喜欢
  • 2017-09-14
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多