简体   繁体   中英

Subtracting days from variable in date and time

I need to subtract 1 day from the current date and time? How would i do that? Here is my code:

from datetime import datetime
now = datetime.now()
date = (now.strftime("%Y-%m-%d %H:%M:%S"))
print(date)

Say the date is (2021-10-3) i need the time variable to be set to something like (2021-10-2) Changing the day by -1 day!

Use timedelta .

from datetime import datetime, timedelta
now = datetime.now()
yesterday = now - timedelta(days=1)
date = (yesterday.strftime("%Y-%m-%d %H:%M:%S"))
print(date)

Find more about timedelta here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM