Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I extract a date format from a string in Python?

If you know the position of the date object in the string (for example in a log file), you can use . split()[index] to extract the date without fully knowing the format.

How do I get the current date in a specific format in Python?

Basically the syntax is - datetime. strftime(format) which will return a string representing date and time using date, time or datetime object. There are many format codes like %Y , %d , %m , etc which you can use to specify the format you want your result to be.


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

#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 a f 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 is 2018-11-11 yay


Description:

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.

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


>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%B %d, %Y")
'July 23, 2010'

If you don't care about formatting and you just need some quick date, you can use this:

import time
print(time.ctime())