Search code examples
pythondatedatetimeseries

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:

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
    import pandas as pd
    
    df = pd.DataFrame({'dates': [(2020, 5, 17), (2020, 12, 12), (2021, 2, 13), (2022, 5, 17)]})
    
    x = []
    
    for i in df['dates']: 
        x.append(datetime.date(*i))
    
    df['formatted_dates'] = x