Open In App

How to Convert String to Datetime in R?

Last Updated : 27 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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




# consider a string
string = "2021-11-21 4:5:23"
 
# convert string to datetime
final = as.POSIXct(string, format="%Y-%m-%d %H:%M:%S", tz="UTC")
 
# display
print(final)
 
# get the type
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




# consider a dataframe
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"))
 
# convert data column  to datetime
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"


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads