Rock
Rock

Reputation: 2967

Extract Hour From "yyyymmddHH"

This is probably asked many times but I couldn't find related resource and just can't get it right. I have a data frame with an HourStamp column in yyyymmddHH format and I need to extract the HH from it. How can I do it?

As an example:

HourStamp  Hour
2013050100   00
2013050101   01
2013050102   02
...

I need that Hour column added. Thanks!

Upvotes: 0

Views: 786

Answers (1)

Paul Hiemstra
Paul Hiemstra

Reputation: 60944

Like @Klaus already commented, in this case a simple substr would to the trick, i.e. substr('2013050100', 9, 10). Remember that substr is vectorized so you can simply do:

df$Hour = substr(df$HourStamp, 9, 10)

A more flexible and powerful way of dealing with dates/times is to simply convert HourStamp into a real R date object:

d = strptime('2013050100', format = '%Y%m%d%H')
strftime(d, '%H')
[1] "00"

In this case the strptime solution is a bit cumbersome, but it allows for stuff like:

> strftime(d, '%A %d of %B in the year %Y')
[1] "Wednesday 01 of May in the year 2013"

or:

strftime(d, 'file%Y%d.csv')
[1] "file201301.csv"

or in vectorized form for your example:

df$time = strptime(df$HourStamp, format = '%Y%m%d%H')
df$Hour = strftime(df$time, '%H')

Upvotes: 8

Related Questions