How do I get a string format of the current date time, in python?


For example, on July 5, 2010, I would like to calculate the string

 July 5, 2010

How should this be done?

4/22/2015 11:15:32 PM

Accepted Answer

You can use the datetime module for working with dates and times in Python. The strftime method allows you to produce string representation of dates and times with a format you specify.

>>> import datetime
>>>"%B %d, %Y")
'July 23, 2010'
>>>"%I:%M%p on %B %d, %Y")
'10:36AM on July 23, 2010'
7/23/2010 9:36:35 AM


import datetime
    '1: test-{date:%Y-%m-%d_%H:%M:%S}.txt'.format( )

d =
print( "2a: {:%B %d, %Y}".format(d))

# see the f" to tell python this is a f string, no format
print(f"2b: {d:%B %d, %Y}")

print(f"3: Today is {} yay")

1: test-2018-02-14_16:40:52.txt

2a: March 04, 2018

2b: March 04, 2018

3: Today is 2018-11-11 yay


Using the new string format to inject value into a string at placeholder {}, value is the current time.

Then rather than just displaying the raw value as {}, use formatting to obtain the correct date format.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow