Home > database >  Combining Year and DayOfYear, H:M:S columns into date time object
Combining Year and DayOfYear, H:M:S columns into date time object

Time:05-25

I have a time column with the format XXXHHMMSS where XXX is the Day of Year. I also have a year column. I want to merge both these columns into one date time object.

Before I had detached XXX into a new column but this was making it more complicated.

I've converted the two columns to strings

points['UTC_TIME'] = points['UTC_TIME'].astype(str)

points['YEAR_'] = points['YEAR_'].astype(str)

Then I have the following line:

points['Time'] = pd.to_datetime(points['YEAR_'] * 1000   points['UTC_TIME'], format='%Y%j%H%M%S')

I'm getting the value errorr, ValueError: time data '137084552' does not match format '%Y%j%H%M%S' (match)

Here is a photo of my columns and a link to the Time columns

CodePudding user response:

works fine for me if you combine both columns as string, EX:

import pandas as pd

df = pd.DataFrame({'YEAR_': [2002, 2002, 2002],
                   'UTC_TIME': [99082552, 135082552, 146221012]})

pd.to_datetime(df['YEAR_'].astype(str)   df['UTC_TIME'].astype(str).str.zfill(9),
               format="%Y%j%H%M%S")
# 0   2002-04-09 08:25:52
# 1   2002-05-15 08:25:52
# 2   2002-05-26 22:10:12
# dtype: datetime64[ns]

Note, since %j expects zero-padded day of year, you might need to zero-fill, see first row in the example above.

  • Related