Is there a way to convert a string containing year and day of year into pandas timestamp?
eg
a_str = '2000120' # year 2000, day 120
I tried:
pd.Timestamp(year=a_str[:4], dayofyear=a_str[4:])
but I get this error
*** TypeError: __new__() got an unexpected keyword argument 'dayofyear'
How to fix this?
You can use %j
which is the day of the year:
In [11]: dt.datetime.strptime("2000120", "%Y%j")
Out[11]: datetime.datetime(2000, 4, 29, 0, 0)
In [12]: pd.to_datetime("2000120", format="%Y%j")
Out[12]: Timestamp('2000-04-29 00:00:00')
Note: Whilst the docs say:
Day of the year as a zero-padded decimal number.
This doesn't apear to be the case (it works even if it's not zero padded):
In [13]: dt.datetime.strptime("200020", "%Y%j")
Out[13]: datetime.datetime(2000, 1, 20, 0, 0)
In [14]: pd.to_datetime("200020", format="%Y%j")
Out[14]: Timestamp('2000-01-20 00:00:00')
I don't think you can use the Timestamp constructor here, you have to use the to_datetime
method (which allows you to pass format
).
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.