0

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

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

1
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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.