VOOZH about

URL: https://www.geeksforgeeks.org/r-language/how-to-convert-string-to-datetime-in-r/

⇱ How to Convert String to Datetime in R? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Convert String to Datetime in R?

Last Updated : 27 Dec, 2021

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.

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

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"
Comment

Explore