jongju
jongju

Reputation: 33

remove milliseconds from Datetime in TZ format

I have a datetime column that contains DateTime in TZ format like:

timestamp = 2021-04-01T04:37:16.528Z

I have to convert/truncate the milliseconds part such that datetime is:


as.POSIXct(timestamp, format="%Y-%m-%dT%H:%M:%OSZ", tz="GMT")

2021-04-01 04:37:16

But when I group by DateTime column for aggregations it still uses the timestamp in milliseconds format and the aggregations are not gettig implemented properly.

I want to truncate not just print the DateTime till seconds only.

Upvotes: 2

Views: 1414

Answers (2)

viols
viols

Reputation: 51

Have you tried lubridate's floor_date function?

timestamp <- "2021-04-01T04:37:16.528Z"

as.POSIXct(timestamp, format="%Y-%m-%dT%H:%M:%OSZ", tz="GMT") %>% 
  floor_date() %>% 
  format(format = "%d.%m.%Y %H:%M:%OS6")

returns "01.04.2021 04:37:17.000000", so the milliseconds are gone.

References: https://lubridate.tidyverse.org/reference/round_date.html

Upvotes: 1

Wimpel
Wimpel

Reputation: 27772

You could drop the miliseconds part from the string, and then convert:

as.POSIXct(gsub("\\.[0-9]+Z", "", timestamp), 
           format="%Y-%m-%dT%H:%M:%S", tz="GMT")

Upvotes: 2

Related Questions