Reputation: 425
I have Dataframe with a date in this format
"Sun Dec 26 2021 08:10:14 GMT+0100"
see the data frame below
Time Account Name Type Product ID Successful
Sun Dec 26 2021 08:10:14 GMT+0100 switch topup MFIN-1-OR undefined
Sun Dec 26 2021 08:10:14 GMT+0100 switch topup MFIN-1-OR undefined
Sun Dec 26 2021 08:10:14 GMT+0100 switch topup MFIN-1-OR undefined
Sun Dec 26 2021 08:10:14 GMT+0100 switch topup MFIN-1-OR undefined
Sun Dec 26 2021 08:10:12 GMT+0100 switch topup MFIN-1-OR TRUE
Sun Dec 26 2021 08:10:12 GMT+0100 switch topup MFIN-1-OR TRUE
Sun Dec 26 2021 08:10:11 GMT+0100 switch topup MFIN-1-OR TRUE
Sun Dec 26 2021 08:10:11 GMT+0100 switch topup MFIN-1-OR TRUE
Sun Dec 26 2021 08:10:11 GMT+0100 switch topup MFIN-1-OR TRUE
Sun Dec 26 2021 08:10:10 GMT+0100 switch topup MFIN-1-OR TRUE
Sun Dec 26 2021 08:10:10 GMT+0100 switch topup MFIN-1-OR TRUE
How do I convert it to something like this format below
"%y/%m/%d %H:%M:%S"
Upvotes: 0
Views: 47
Reputation: 887541
This may be automatically parsed with parse_date
from parsedate
library(parsedate)
df1$Time <- format(parse_date(df1$Time), "%y/%m/%d %H:%M:%S")
-output
> df1
Time x y
1 21/12/26 08:10:14 1 4
2 21/12/26 08:10:14 2 5
3 21/12/26 08:10:14 3 6
df1 <- structure(list(Time = c("Sun Dec 26 2021 08:10:14 GMT+0100",
"Sun Dec 26 2021 08:10:14 GMT+0100", "Sun Dec 26 2021 08:10:14 GMT+0100"
), x = 1:3, y = 4:6), class = "data.frame", row.names = c(NA,
-3L))
Upvotes: 2
Reputation: 79174
We could use mdy_hms
function of lubridate
package after some tweaking: i.e removing everything before first and after last space:
Thanks to @jay.sf for the data:
library(dplyr)
library(lubridate)
dat %>%
mutate(Time = gsub(" [^ ]*$|^[^ ]* ","",Time,perl=T),
Time = mdy_hms(Time)) %>%
as_tibble()
Time x y
<dttm> <int> <int>
1 2021-12-26 08:10:14 1 4
2 2021-12-26 08:10:14 2 5
3 2021-12-26 08:10:14 3 6
Upvotes: 1
Reputation: 73352
Using strptime
.
strftime(strptime('Sun Dec 26 2021 08:10:14 GMT+0100',
'%a %b %d %Y %H:%M:%S GMT%z'), '%y/%m/%d %H:%M:%S'
)
# [1] "21/12/26 08:10:14"
In your data frame:
transform(dat, Time=strftime(strptime(Time, '%a %b %d %Y %H:%M:%S GMT%z'),
'%y/%m/%d %H:%M:%S'))
# Time x y
# 1 21/12/26 08:10:14 1 4
# 2 21/12/26 08:10:14 2 5
# 3 21/12/26 08:10:14 3 6
Data:
dat <- structure(list(Time = c("Sun Dec 26 2021 08:10:14 GMT+0100",
"Sun Dec 26 2021 08:10:14 GMT+0100", "Sun Dec 26 2021 08:10:14 GMT+0100"
), x = 1:3, y = 4:6), class = "data.frame", row.names = c(NA,
-3L))
Upvotes: 2