简体   繁体   中英

Converting from week number to datetime not working: “time data '201T' does not match format '%Y' (match)”

I currently have a dataframe series that has an output in the format of YWW, where the WW stands for work week.

I've converted this into two new columns, one for the work week and one for the year like so:

derp = pd.DataFrame();
derp['Releasedate'] = sndf['Releasedate'] #releasedate is a string
derp['Week'] = sndf.Releasedate.str.slice(start=4);
derp['Year'] = sndf.Releasedate.str.slice(stop=4);
derp['Year'] = '201' + derp['Year'].astype(str);
derp=derp.dropna()

giving me a dataframe with the following output:

__|Releasedate|Week|Year
0 | 728 | 28 |2017
1 | 742 |42 |2017
2 | 920 | 20 |2019
3 | 813 | 13 |2008

However, when I try converting it to datetime with the following code

derp['New'] = pd.to_datetime(derp.Year.astype(str), format='%Y') + \
             pd.to_timedelta(derp.Week.mul(7).astype(str) + ' days')

It gives me the following error:
ValueError: time data '201T' does not match format '%Y' (match)

How do I overcome this error?

Thank you for your help!

Your conversion is more complicated than needed. Try this:

derp['New'] = pd.to_datetime(derp['Year'], format='%Y') \
                + pd.to_timedelta(derp['Week'].mul(7), unit='d')

Result:

2017-07-16
2017-10-22
2019-05-21
2008-04-01

you have to convert the week numbers to int if you want to multiply them with 7. If you do it with them as strings you will instead get 44 seven time after one another.

This should do it

import pandas as pd

data = {'Releasedate':['744','812']}
sndf = pd.DataFrame(data)
derp = pd.DataFrame()
derp['Releasedate'] = sndf['Releasedate'] #releasedate is a string
derp['Week'] = sndf.Releasedate.str.slice(start=1);
derp['Year'] = sndf.Releasedate.str.slice(stop=1);
derp['Year'] = '201' + derp['Year'].astype(str);
derp=derp.dropna()

derp['New'] = pd.to_datetime(derp.Year.astype(str), format='%Y') + \
             pd.to_timedelta(derp.Week.astype(int).mul(7).astype(str) + ' days')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM