Andrew King
Andrew King

Reputation: 145

How to change strings in dataframe to date time values?

I have a column in a pandas dataframe of strings representing dates in the form

 Year-day hour:minute:second.microsecond

Except the day is written as a single number from 0-364. For example, the date2019-040 04:00:00:000000 represents 4 am on february 9, 2019. How do I convert these values to date time instances?

Upvotes: 1

Views: 27

Answers (2)

Alexis Drakopoulos
Alexis Drakopoulos

Reputation: 1145

What you are really asking is, what is the directive of days of the year padded with 0. It's "%j".

So in this case you would do %Y for year, %j for day, %H for hour, %M for minute, %S for seconds, %f for microseconds.

pd.to_datetime(column, format='%Y-%j %H:%M:%S:%f')

Upvotes: 0

TomNash
TomNash

Reputation: 3288

You can use datetime and strptime to achieve this. The %j directive allows you to enter the zero-padded day number of the year:

import datetime as dt
date_time = '2019-040 04:00:00:000000'
dt.datetime.strptime(date_time, '%Y-%j %H:%M:%S:%f')

Output:

datetime.datetime(2019, 2, 9, 4, 0)

Upvotes: 2

Related Questions