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

How to reproduce a spared series of dates by using an iteration method

I am trying to create a column to add to an original dataset containing dates. Specifically, I was looking for a quick and smart method (any with iteration, if possible) to convert a string into a series of dates. In short, the result I expect is the following one:

2020 - 5 - 17
2020 - 12 - 12 
2021 - 2 - 13 
2022 - 5 - 17

I have tried the following code:

dates = [(2020, 5, 17), (2020, 12, 12), (2021, 2, 13), (2022, 5, 17)]

    for i in dates: 
        datetime.date(i)
        print(i)

That turns me back to the following error:

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

TypeError: an integer is required (got type tuple)

Could someone please suggest how to text a nice code to get what I looking for? Thanks

>Solution :

Use this:

import datetime
dates = [(2020, 5, 17), (2020, 12, 12), (2021, 2, 13), (2022, 5, 17)]
for i in dates: 
    x = datetime.date(*i)
    print(x)

Output:

2020-05-17
2020-12-12
2021-02-13
2022-05-17

If inserting into a dataframe:

import datetime

dates = [(2020, 5, 17), (2020, 12, 12), (2021, 2, 13), (2022, 5, 17)]
x = []

for i in dates: 
    x.append(datetime.date(*i))

df['x'] = x
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