How to get string format of current date time in python?

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

July 5, 2010 

How to do it?

+92
python datetime
Jul 23 '10 at 9:24
source share
4 answers

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

 >>> import datetime >>> datetime.date.today().strftime("%B %d, %Y") 'July 23, 2010' >>> datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y") '10:36AM on July 23, 2010' 
+200
Jul 23 '10 at 9:28
source share
 #python3 import datetime print( '1: test-{date:%Y-%m-%d_%H:%M:%S}.txt'.format( date=datetime.datetime.now() ) ) d = datetime.datetime.now() print( "2a: {:%B %d, %Y}".format(d)) # see the f" to tell python this is af string, no format print(f"2b: {d:%B %d, %Y}") print(f"3: Today is {datetime.datetime.now():%Y-%m-%d} yay") 

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

2a: March 04, 2018

2b: March 04, 2018

3: today 2018-11-11




Description:

Using the new row format to insert a value into a row in the placeholder {}, the value is the current time.

Then, instead of simply displaying the raw value as {}, use formatting to get the correct date format.

https://docs.python.org/3/library/string.html#formatexamples

+24
Feb 14 '18 at 3:42
source share
 >>> import datetime >>> now = datetime.datetime.now() >>> now.strftime("%B %d, %Y") 'July 23, 2010' 
+23
Jul 23 '10 at 9:29
source share

If you are not interested in formatting and you just need a small date, you can use this:

 import time print(time.ctime()) 
+3
Jan 25 '19 at 2:56
source share



All Articles