1

I would like to create a data frame in which I have a column of POSIXlt data.

In the following way, unfortunately the time zone is lost and the time is shifted by one hour (I'm in Switzerland)

df <- data.frame(
  DateTime=c(
    strptime("2020-02-01T06:00", "%Y-%m-%dT%H:%M", tz = "UTC"),
    strptime("2020-02-01T06:00", "%Y-%m-%dT%H:%M", tz = "UTC")
  ),
  Name=c(
    "John",
    "Carl"
  )
)
print(df$DateTime)

gives:

[1] "2020-02-01 07:00:00 CET" "2020-02-01 07:00:00 CET"

The only possible workaround is as follows:

df <- data.frame()
df <- rbind(df,
            data.frame(DateTime=strptime("2020-02-01T06:00", "%Y-%m-%dT%H:%M", tz = "UTC"), Name="John"),
            data.frame(DateTime=strptime("2020-02-01T06:00", "%Y-%m-%dT%H:%M", tz = "UTC"), Name="Carl")
)
print(df$DateTime)

gives:

[1] "2020-02-01 06:00:00 UTC" "2020-02-01 06:00:00 UTC"

I have already established that the problem lies in the vector:

x <- strptime("2020-02-01T06:00", "%Y-%m-%dT%H:%M", tz = "UTC")

gives:

[1] "2020-02-01 06:00:00 UTC"

but:

x <- c(strptime("2020-02-01T06:00", "%Y-%m-%dT%H:%M", tz = "UTC"))

gives:

[1] "2020-02-01 07:00:00 CET"

Why does wrapping the POSIXlt value in a vector changes the value itself?

Davide
  • 1,931
  • 2
  • 19
  • 39
  • I cannot reproduce this; the first command returns `"2020-02-01 06:00:00 UTC"`. – r2evans Jan 13 '22 at 13:02
  • Note that `?DateTimeClasses` says: *Using ‘c’ on ‘"POSIXlt"’ objects converts them to the current time zone, and on ‘"POSIXct"’ objects drops any ‘"tzone"’ attributes, unless they are all marked with the same time zone.* – G. Grothendieck Jan 13 '22 at 13:23
  • Related (more focus on `POSIXct`): [Guard against accidental time-zone conversion](https://stackoverflow.com/questions/7665605/guard-against-accidental-time-zone-conversion); [Odd POSIXct Function Behavior In R](https://stackoverflow.com/questions/32489458/odd-posixct-function-behavior-in-r); [combining POSIXct gives wrong hours](https://stackoverflow.com/questions/52669633/combining-posixct-gives-wrong-hours) – Henrik Jan 13 '22 at 13:33

0 Answers0