3

I have a time data in a column and trying to figure out how can I get it in datetime format

2000
2100
2300
2355
0
1
5 
10
100
105
330

My question is how can I get these in datetime format:

output should be:

20:00:00
21:00:00
23:00:00
23:55:00
00:00:00
00:01:00
00:05:00
00:10:00
01:00:00
01:05:00
03:30:00

tried:

1. da =  pd.to_datetime(330, format='%H%M')
   output: '03:30:00'

2. d= str(datetime.timedelta(minutes = 55 ))
   output : '0:55:00'

But if I apply 1. to 100 it gives 10 hrs.

   eg: da =  pd.to_datetime(100, format='%H%M')
   output: '10:00:00'
1
  • Your question is getting three answers already! Nice. Commented May 6, 2019 at 18:35

3 Answers 3

3

Try,

pd.to_datetime(df['time'].astype(str).str.zfill(4), format = '%H%M').dt.time


0     20:00:00
1     21:00:00
2     23:00:00
3     23:55:00
4     00:00:00
5     00:01:00
6     00:05:00
7     00:10:00
8     01:00:00
9     01:05:00
10    03:30:00
Sign up to request clarification or add additional context in comments.

1 Comment

originally when I loaded the test data it was dtype: int64 I was thinking on altering that as int64, but then I realized it is to_datetime needs a string. :)
2

IIUC str.rjust

pd.to_datetime(s.astype(str).str.rjust(4,'0'),format='%H%M').dt.time
Out[41]: 
0     20:00:00
1     21:00:00
2     23:00:00
3     23:55:00
4     00:00:00
5     00:01:00
6     00:05:00
7     00:10:00
8     01:00:00
9     01:05:00
10    03:30:00
Name: x, dtype: object

1 Comment

maybe zfill could be nice
0

Since novice code, I am making the things more explicit and adding the formatting letters %H and %M info:

df['cname'] = pd.to_datetime(df['cname'].astype(str).str.zfill(4), format = '%H%M').dt.time
print(df['cname'])

# %H    Hour (24-hour clock) as a zero-padded decimal number.   07
# %M    Minute as a zero-padded decimal number.     06

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.