I am looking to get today's date
and n
- today's date
in the format below: -
tod = datetime.datetime.now()
d = datetime.timedelta(days = 365)
x = tod - d
I want x
and tod
in YYYYMMDD format for eg: 20230130 How do I get it to this format
the datetime
class has an strftime
function that allows you to convert a datetime to string in the format you set (more info here: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes ).
import datetime
tod = datetime.datetime.now()
d = datetime.timedelta(days = 365)
x = tod - d
print(x.strftime("%Y%m%d"))
output:
20230130
import datetime
tod = datetime.datetime.now()
d = datetime.timedelta(days = 365)
x = tod - d
#Before formatting
#print(d) #365 days, 0:00:00
#print(x) #2022-01-30 05:59:48.328091
#strftime can be used to format as your choice %Y for year, %m for month, %d for date
tod_ = tod.strftime("%Y%m%d")
x_ = x.strftime("%Y%m%d")
print(tod_) #20230130
print(x_) #20220130
A similar answer is here Convert datetime object to a String of date only in Python . It use datetime.datetime.strftime
method to work. For example in your case:
import datetime
tod = datetime.datetime.now()
d = datetime.timedelta(days = 365)
x = tod - d
print(x.strftime('%Y%m%d'))
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.