Reputation: 2329
I would like to extract the hour/minute/second from a datetime. Example dataframe:
df <- structure(list(Study_date_time_PACS = structure(c(1515146548, 1515146548, 1514970658, 1514970658, 1515151732, 1515151732, 1517476589, 1517476589, 1543848246, 1543848246),
class = c("POSIXct", "POSIXt"),
tzone = "UTC")),
.Names = "Study_date_time",
row.names = c(NA, -10L),
class = c("tbl_df", "tbl", "data.frame"))
print(df)
# A tibble: 10 x 1
Study_date_time
<dttm>
1 2018-01-05 10:02:28
2 2018-01-05 10:02:28
3 2018-01-03 09:10:58
4 2018-01-03 09:10:58
5 2018-01-05 11:28:52
6 2018-01-05 11:28:52
7 2018-02-01 09:16:29
8 2018-02-01 09:16:29
9 2018-12-03 14:44:06
10 2018-12-03 14:44:06
So I run this code but it adds one hour to the "hour"? How can I fix this. I assume it must be something with summertime...
library(lubridate)
df %>%
mutate(hour_min = hms::as.hms(Study_date_time))
# A tibble: 10 x 2
Study_date_time hour_min
<dttm> <time>
1 2018-01-05 10:02:28 11:02
2 2018-01-05 10:02:28 11:02
3 2018-01-03 09:10:58 10:10
4 2018-01-03 09:10:58 10:10
5 2018-01-05 11:28:52 12:28
6 2018-01-05 11:28:52 12:28
7 2018-02-01 09:16:29 10:16
8 2018-02-01 09:16:29 10:16
9 2018-12-03 14:44:06 15:44
10 2018-12-03 14:44:06 15:44
Upvotes: 0
Views: 275
Reputation: 14764
I agree that this likely a tz
issue (perhaps you can just do hms::as.hms(Study_date_time, tz = 'UTC'))
and it'll disappear), however I think you'd also do good without any package, e.g.:
df %>%
mutate(hour_min = format(Study_date_time, "%H:%M"))
Upvotes: 0
Reputation: 27762
Probaby due to the timezone-element that gets stripped... Let me guess: You live in a UTC+0100 - region of the planet?
You can use the force_tz()
function from the lubridate-package.. but be careful!! Timezones are always a b#tch to work with, so handle with care!
df %>% mutate(hour_min = hms::as.hms( force_tz( Study_date_time ) ) )
# # A tibble: 10 x 2
# Study_date_time hour_min
# <dttm> <time>
# 1 2018-01-05 10:02:28 10:02
# 2 2018-01-05 10:02:28 10:02
# 3 2018-01-03 09:10:58 09:10
# 4 2018-01-03 09:10:58 09:10
# 5 2018-01-05 11:28:52 11:28
# 6 2018-01-05 11:28:52 11:28
# 7 2018-02-01 09:16:29 09:16
# 8 2018-02-01 09:16:29 09:16
# 9 2018-12-03 14:44:06 14:44
# 10 2018-12-03 14:44:06 14:44
Upvotes: 1