Get the current date in Python

Datetime: date time module, which provides multiple methods to operate date and time

Strftime: format date and time

Get today’s date, yesterday’s date, formatted date

>>> import datetime
>>> today=datetime.date.today()
>>> print today
2018-01-17
>>> formatted_today=today.strftime('%y%m%d')
>>> print formatted_today
180117
>>> yesterday=int(formatted_today)-1
>>> print yesterday
180116

The above content was written on January 17, 2018. Now some problems are found on March 1. When it crosses months, the above code will appear.

yesterday=int(formatted_today)-1

After executing this line of code, the day before March 1 becomes March 0

How to change it?

yesterday = (datetime.date.today() + datetime.timedelta(days=-1)).strftime('%Y%m%d')

Get today’s date first

Then use the timedetla object of datetime, which represents the difference between the two times, datetime.timedelta (days = – 1) means the time of the day before. The day before March 1 is February 28.

Finally, we use strftime to transform the time format

Read More: