1

I have had a good hunt around and sure this has to have been answered before but I cant seem to find any help!

I have a series of times in a data frame, some of which have the following time stamp in the following format:

Date <- '2018-10-10'
Time <- '00:00:00'

When I use the strptime function it returns only the date, it removes the 00:00:00, see below:

datetime <- strptime(paste(Date,Time),
                     format = "%Y-%m-%d %H:%M:%S",
                     tz = 'GMT')

> datetime
[1] "2018-10-10 GMT"

if for example it was Time <- 00:00:01 it would return

> datetime
[1] "2018-10-10 00:00:01 GMT"

Does anyone know a way of ensuring the output for 00:00:00 instances are displayed. Desired output:

"2018-10-10 00:00:00 GMT"

Many thanks!!

Jim

Henrik
  • 65,555
  • 14
  • 143
  • 159
Jim
  • 558
  • 4
  • 13
  • 1
    Use `strftime` with `datetime` to create a character string witth a specific format. – Roland May 09 '19 at 12:16
  • 1
    Under the hood `print.POSIXct` calls `format`. From `?format`: "The default for the format methods is `"%Y-%m-%d %H:%M:%S"` if any element has a time component which is not midnight, and `"%Y-%m-%d"` otherwise.". – Henrik May 09 '19 at 12:26
  • Cheers, I did have a good luck I didnt even think about calling it 'midnight' – Jim May 09 '19 at 16:09

1 Answers1

1

When you type datetime and hit <Enter>, R will use a/the suitable print method to display datetime. Just because datetime returns "2018-10-10 GMT" doesn't mean that datetime has forgotten about the seconds.

To ensure a consistent format of your POSIXlt object, you could use format

format(datetime, "%Y-%m-%d %H:%M:%S", usetz = T)
#[1] "2018-10-10 00:00:00 GMT"

Similar for case 2

Date <- '2018-10-10'
Time <- '00:00:01'
datetime <- strptime(paste(Date,Time), format = "%Y-%m-%d %H:%M:%S", tz = 'GMT')
format(datetime, "%Y-%m-%d %H:%M:%S", usetz = T)
#[1] "2018-10-10 00:00:01 GMT"

Sample data

Date <- '2018-10-10'
Time <- '00:00:00'
datetime <- strptime(paste(Date,Time), format = "%Y-%m-%d %H:%M:%S", tz = 'GMT')
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • awesome! worked a treat cheers, I thought it would be hiding there somewhere, but it doesnt print it during write.csv either. Many thanks – Jim May 09 '19 at 16:10