+2 votes
in Programming Languages by (7.6k points)
I want to print current date in 'YYYY-MM-DD' format and curret time in 'HH-MM-SS' format. How can I find current date and time in python?

1 Answer

0 votes
by (14.8k points)

You can use today() function of datetime library to get year, month, day, hour, minute, second, and microsecond. Then you need to use some String manipulation to get the current date and time in your desired format.

>>> from datetime import datetime

>>> datetime.today()

datetime.datetime(2018, 7, 31, 16, 46, 57, 768000)

>>> yyyy=str(datetime.today().year)

>>> mm=str(datetime.today().month) if datetime.today().month >9 else '0'+str(datetime.today().month)

>>> dd=str(datetime.today().day)

>>> cdate=yyyy + '-' + mm + '-' + dd

>>> cdate

'2018-07-31'

>>> hh = str(datetime.today().hour) if datetime.today().hour>9 else '0'+str(datetime.today().hour)

>>> mm = str(datetime.today().minute) if datetime.today().minute>9 else '0'+str(datetime.today().minute)

>>> ss = str(datetime.today().second) if datetime.today().second>9 else '0'+str(datetime.today().second)

>>> ctime=hh + '-' + mm + '-' + ss

>>> ctime

'19-03-29'

Related questions

...