'Retrieving day and time (in minutes) from character timestamp
I have a timestamp in character in the following format with a suffixed Z
:
"2022-03-01T00:00:00Z"
I wanted to retrieve the day in numbers and the time in minutes (should return 0 from the above example).
I tried the execute the following code but my output only retrieve the year-month-day and not the time format.
time_stamp <- as.POSIXct(participant1_data$timestamp[1], format="%Y-%m-%dT%H:%M")
str(time_stamp)
Output: POSIXct[1:1], format: "2022-03-01"
Is there anything wrong with the code that does not retrieve the time format?
Solution 1:[1]
As noted in comments, use
tz="UTC"
, otherwise the "Z" == UTC (zulu) information gets lost, also see this answer.If time is exactly midnight, the output is omitted.
as.POSIXct('2022-03-01T00:00:00Z', tz="UTC", "%Y-%m-%dT%H:%M:%OSZ")
# [1] "2022-03-01 UTC"
as.POSIXct('2022-03-01T11:11:11Z', tz="UTC", "%Y-%m-%dT%H:%M:%OSZ")
# [1] "2022-03-01 11:11:11 UTC"
- You have now read in the time correctly and got
"POSIXct"
class. To achieve a different output from it, you need to format it to character with the desired format usingstrftime
which allows to specify the correct timezonetz=
, e.g."CET"
.
strftime(as.POSIXct('2022-03-01T00:00:00Z', tz="UTC", "%Y-%m-%dT%H:%M:%OSZ"),
'%F %R', tz='CET')
# [1] "2022-03-01 01:00"
strftime(as.POSIXct('2022-03-01T11:11:11Z', tz="UTC", "%Y-%m-%dT%H:%M:%OSZ"),
'%F %R', tz='CET')
# [1] "2022-03-01 12:11"
Or if I understand "day in numbers and the time in minutes correctly, you maybe want this:
strftime(as.POSIXct('2022-03-01T11:11:11Z', tz="UTC", "%Y-%m-%dT%H:%M:%OSZ"),
'%d %M', tz='CET')
# [1] "01 11"
Type help('strftime')
or short ?strftime
into the R console and read the help page for possible in/output options.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |