Open In App

How to Convert Character to a Timestamp in R?

In this article, we will convert character to timestamp in R Programming Language.

We can convert the character to timestamp by using strptime() method. strptime() function in R Language is used to parse the given representation of date and time with the given template.



Syntax

strptime(character, format, tz = “”)

Where,  



Example 1: Convert character to year , month and date format timestamp




# create character
character = "2021-4-4"
 
# convert character with year month and date format
print(strptime(character, "%Y-%m-%d"))

Output:

[1] "2021-04-04 UTC"

Example 2: R program to convert character into timestamp




# create character
character = "2021-4-4 02:23:34"
 
# convert character with year month date
# and Hours minutes and seconds format
print(strptime(character, "%Y-%m-%d %H:%M:%S"))

Output:

[1] "2021-04-04 02:23:34 UTC"

Example 3: In this example, we are going to specify the timezone




# create character
character = "2021-4-4 02:23:34"
 
# convert character with year month date
# and Hours minutes and seconds format
# and specify time zone as UTC
print(strptime(character, "%Y-%m-%d %H:%M:%S",tz="UTC"))

Output:

[1] "2021-04-04 02:23:34 UTC"

Article Tags :