Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date time to a formatted time string

Tags:

I don't know why it doesn't work. Here is my code:

> t <- hms("14:11:49") > t [1] "14H 11M 49S" t <- t + minutes(3) > format(t, format="%H:%M:%S") [1] "14H 14M 49S" # Expected output: "14:14:49" 

Update:

Currently I found this solution, but I hope there is a more elegant one:

t <- hms("14:11:49") # example period object sprintf("%s:%s:%s", hour(t), minute(t), second(t)) #"14:11:49" 
like image 673
biocyberman Avatar asked Sep 04 '14 14:09

biocyberman


People also ask

How do I convert a datetime to a string?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do I convert a datetime to a specific format?

The ToString() method of the DateTime class is used to convert a DateTime date object to string format. The method takes a date format string that specifies the required string representation.

What is string date/time format?

A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results from a formatting operation. It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time.

How do I convert a date to a string in SQL?

In order to convert a DateTime to a string, we can use CONVERT() and CAST() function. These functions are used to converts a value(of any datatype) into a specified datatype.


1 Answers

Not sure why you need to convert to hms and back to initial string format. Maybe parse_date_time function is what you need:

library(lubridate) myTime <- "14:11:49" hms(myTime) #"14H 11M 49S"  POSIXct_myTime <- parse_date_time(myTime,"hms") format(POSIXct_myTime, format="%H:%M:%S") #"14:11:49" 

EDIT: We can use paste:

t <- hms("14:11:49") t #[1] "14H 11M 49S" t <- t + minutes(3) t #[1] "14H 14M 49S"  paste(hour(t),minute(t),second(t),sep=":") #[1] "14:14:49" 

Benchmark output:

op <- microbenchmark(   Use_paste=paste(hour(t),minute(t),second(t),sep=":"),   Use_sprintf=sprintf("%s:%s:%s", hour(t), minute(t), second(t)),   times=1000000L) op  # Unit: microseconds # expr    min     lq median     uq      max neval # Use_paste 28.072 31.695 32.601 33.506 44253.42 1e+06 # Use_sprintf 29.582 33.807 34.412 35.619 44367.52 1e+0 
like image 158
zx8754 Avatar answered Sep 30 '22 10:09

zx8754