-2
>>> mtime
1634725796.7212281
>>> from datetime import datetime
>>> datetime.fromtimestamp(mtime)
datetime.datetime(2021, 10, 20, 15, 59, 56, 721228)
>>>

I want date-time string returned exactly in the format Date: Wed, 20 Oct 2021 15:59:56 GMT which is the format a server sends when the page was last modified.

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

anjanesh
  • 3,771
  • 7
  • 44
  • 58

1 Answers1

0

You need to use the datetime.strftime function to format the datetime.

If your datetime doesn't have a timezone:

>>> 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 

If your datetime object is timezone aware:

Use the %Z format option to get the timezone in the format string.

Ron
  • 168
  • 9
  • 2
    This is risky, you're completely ignoring whether or not the datetime is actually GMT (or timezone-aware at all). – jonrsharpe Oct 27 '21 at 11:08
  • This is more straight-forward : `from email.utils import formatdate; print(formatdate(mtime, usegmt=True))` – anjanesh Oct 28 '21 at 09:26
  • @jonrsharpe That is true, but the timezone info isn't available from the timestamp. That is dependent on the system and needs to be fetched from the OS. – Ron Oct 28 '21 at 12:11
  • A timestamp _is_ in UTC, by definition. But my point is that your answer shows a naive datetime, which will be _local_, and just slaps a possibly-incorrect "GMT" on the end. The comment by MrFuppes above shows how to create an aware datetime from a timestamp, for example. – jonrsharpe Oct 28 '21 at 13:17
  • @jonrsharpe I was skeptic about the hardcoded GMT myself. I've updated my answer. – Ron Oct 28 '21 at 13:48