Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dates appearing in list as datetime.date(YYYY,M,D)

I have a script that is printing the dates at a certain interval between a start date and an end date that is specified by the user. The dates are being printed in the format YYYY-MM-DD as in 2023-06-08. This is the format I like.

In addition to printing the dates, I added some code that is appending these dates to a list. However, when I run this code, the same dates are being entered into the list as [datetime.date(2023,6,1)]. Is there a way around this?

sections = []


#year month day format
barstartdate = datetime.date(int(startyear),int(startmonth),int(startday))
#year month day format
barenddate = datetime.date(int(endyear),int(endmonth),int(endday))
#delta time
delta = datetime.timedelta(days=7)
#iterate over range of dates
while (barstartdate <= barenddate):
    print(barstartdate, end="\n")
    sections.append(barstartdate)
    barstartdate += delta

print(sections)

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2023-06-01
2023-06-08
[datetime.date(2023, 6, 1), datetime.date(2023, 6, 8)]

For reference, the start date and stop date in this case was 2023-06-01 and 2023-06-14. The last bit of code shown is the output I am getting in my console. The first two dates are appearing as I want them to, but the list has an odd format. How do I fix this?

>Solution :

When you print an object it will convert the object to a string using the str() built-in. However, when you print a list, the objects inside the list will be converted using repr().

For many classes str() and repr() will return the same string, but not for date objects:

>>> str(datetime.date.today())
'2023-06-15'

>>> repr(datetime.date.today())
'datetime.date(2023, 6, 15)'

What you are seeing in the list is the string representation of a datetime.date instance. You need to convert them to strings using .strftime("%Y-%m-%d") or, in your case, using the shortcut method .isoformat().

Try replacing

sections.append(barstartdate)

with

sections.append(barstartdate.isoformat())

Additi

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading