How to Convert String to Datetime in R?
In this article, we will discuss how to convert String to Datetime in R Programming Language. We can convert string to DateTime by using the POSIXct function
Syntax: as.POSIXct(string, format=”%Y-%m-%d %H:%M:%S”, tz=”UTC”)
where
- string is the input string
- format represents the datetime format
- tz specifies local time zone
Example 1: Convert One String to Datetime
Here we are going to take a string as input and convert it to DateTime.
R
string = "2021-11-21 4:5:23"
final = as.POSIXct (string, format= "%Y-%m-%d %H:%M:%S" , tz= "UTC" )
print (final)
class (final)
|
Output:
[1] "2021-11-21 04:05:23 UTC"
[1] "POSIXct" "POSIXt"
Example 2: Convert Column of Strings to Datetime
Here we are taking a string from dataframe and then convert into DateTime
Syntax: as.POSIXct(dataframe$column_name, format=”%Y-%m-%d %H:%M:%S”, tz=”UTC”)
where,
- dataframe is the input dataframe
- column_name is the string datetime column
R
dataframe = data.frame (data = c ( "2021-11-21 4:5:23" ,
"2021-11-22 4:5:23" ,
"2021-11-23 4:5:23" ,
"2021-11-24 4:5:23" ,
"2021-11-25 4:5:23" ))
print ( as.POSIXct (dataframe$data,
format= "%Y-%m-%d %H:%M:%S" ,
tz= "UTC" ))
|
Output:
[1] "2021-11-21 04:05:23 UTC" "2021-11-22 04:05:23 UTC"
[3] "2021-11-23 04:05:23 UTC" "2021-11-24 04:05:23 UTC"
[5] "2021-11-25 04:05:23 UTC"
Last Updated :
27 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...