0

Using datetime.datetime.now(), I receive some badly formatted timestamps.

Is there an intuitive way of creating a date timestamp in this format?

Wed Aug 7 13:38:59 2019 -0500

This is seen in git log.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • Have a look at the `strftime()` method of `datetime` instance objects. – John Gordon Aug 07 '19 at 19:33
  • Possible duplicate of [How to print a date in a regular format?](https://stackoverflow.com/questions/311627/how-to-print-a-date-in-a-regular-format) – TemporalWolf Aug 07 '19 at 19:33
  • 1
    https://docs.python.org/3.7/library/datetime.html#strftime-and-strptime-behavior – Alexander Aug 07 '19 at 19:34
  • If you are using this for logging it's best to use a [log formatter](https://stackoverflow.com/questions/3220284/how-to-customize-the-time-format-for-python-logging) for this. – blues Aug 07 '19 at 19:37

3 Answers3

2

You can use datetime.datetime.strftime() to format dates as shown below:

from datetime import datetime
d = '2019-08-07 13:38:59-0500'
d2 = datetime.strptime(d, '%Y-%m-%d %H:%M:%S%z')
d3 = d2.strftime('%a %b %d %H:%M:%S %Y %z')
print(d3)

This returns:

Wed Aug 07 13:38:59 2019 -050000

This website is a great resource for strftime formatting.

jdub
  • 170
  • 10
0

You can still use the datetime library. Using strftime, you can rewrite the datetime object into a nicely formatted string.

In your case, you are going for Wed Aug 7 13:38:59 2019 -0500, which translated to strftime formatting is "%a %b %d %H:%M:%S %Y %z".

Overall, it'd be

datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Y %z")

Which will give a string that looks like 'Wed Aug 7 13:38:59 2019 -0500'.

PoorProgrammer
  • 459
  • 1
  • 4
  • 14
0

I would do the following:

from time import gmtime, strftime

if __name__ == "__main__":
    time = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
    print(time)

This was found on the documentation page of the time module. There are also a lot of additional features you might be interested in using outlined here: https://docs.python.org/3/library/time.html#time.strftime

Blonded
  • 137
  • 1
  • 11