Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to preserve midnight timestamp in R when converting from MDY-HMS to YMD-HMS

I have a character string that gives a date and an a time stamp in the MDY-HMS format
"12/14/23 12:00:00 AM"

When I use the mdy_hms function in lubridate to re-format the string as YMD-HMS, the timestamp is gone.

What can be done to make sure that the midnight timestamp is preserved?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I use the mdy_hms function in lubridate to re-format the string as YMD-HMS, the timestamp is gone.

mdy_hms("12/14/23 12:00:00 AM")

"2023-12-14 UTC"

I’ve tested the mdy_hms function by replace the 12 in the hour as 00 and it gives the same result, but when the timestamp portion of the string is either 12:01:00 AM or 00:01:00 AM, the timestamp is preserved.

mdy_hms("12/14/23 12:01:00 AM")

"2023-12-14 00:01:00 UTC"

"2023-12-14 00:01:00 UTC"

I want the output to be "2023-12-14 00:00:00 UTC"

>Solution :

It’s not gone. It just how the value is printed out per default.

ala <- lubridate::mdy_hms("12/14/23 12:00:00 AM")
ala
#> [1] "2023-12-14 UTC"

Use format() to change it. And the computations (time difference) works properly:

format(ala, "%Y-%m-%d %H:%M:%S")
#> [1] "2023-12-14 00:00:00"

ola <- lubridate::mdy_hms("12/14/23 01:00:00 PM")

ola - ala
#> Time difference of 13 hours

Created on 2024-03-15 with reprex v2.1.0

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading