0

I wrote this to generate a list of months starting from the end of last month and going 12 months back in the format 2022-09-30. I have the following code as a starting point:

base = datetime.datetime.today()
date_list = [base - relativedelta(months=x) for x in range(12)]
date_list

[datetime.datetime(2022, 10, 12, 13, 18, 17, 747024),
 datetime.datetime(2022, 9, 12, 13, 18, 17, 747024),
 datetime.datetime(2022, 8, 12, 13, 18, 17, 747024),
 datetime.datetime(2022, 7, 12, 13, 18, 17, 747024),
 datetime.datetime(2022, 6, 12, 13, 18, 17, 747024),
 datetime.datetime(2022, 5, 12, 13, 18, 17, 747024),
 datetime.datetime(2022, 4, 12, 13, 18, 17, 747024),
 datetime.datetime(2022, 3, 12, 13, 18, 17, 747024),
 datetime.datetime(2022, 2, 12, 13, 18, 17, 747024),
 datetime.datetime(2022, 1, 12, 13, 18, 17, 747024),
 datetime.datetime(2021, 12, 12, 13, 18, 17, 747024),
 datetime.datetime(2021, 11, 12, 13, 18, 17, 747024)]

I don't know how to change this to a list that always shows the end of the last month and into the format I want, and I can see that the first three numbers are year - month - day, what are the other numbers? Thanks for any help!

user13948
  • 443
  • 1
  • 6
  • 14
  • it's a dateTIME object so you have year, month, day, hour, minute, second, nanoseconds. You can use `strftime()` on the objects to create a string in your desired format. – vaizki Oct 12 '22 at 13:26
  • Check out https://stackoverflow.com/a/14994380 and https://docs.python.org/3/library/datetime.html#datetime.date.strftime – gvee Oct 12 '22 at 13:28

1 Answers1

1

You can use strftime,

In [1]: base = datetime.datetime.today()
   ...: date_list = [(base - relativedelta(months=x)).strftime('%Y-%m-%d') for x in range(12)]

In [2]: date_list
Out[2]: 
['2022-10-12',
 '2022-09-12',
 '2022-08-12',
 '2022-07-12',
 '2022-06-12',
 '2022-05-12',
 '2022-04-12',
 '2022-03-12',
 '2022-02-12',
 '2022-01-12',
 '2021-12-12',
 '2021-11-12']
 
Rahul K P
  • 15,740
  • 4
  • 35
  • 52