Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dates, timezone and POSIXct

I just fread a large datafile, and the "DATE" column is stored as character like O5JAN2004, 06JAN2004.The time in this datafile is matched to NewYork time, and I live in Los Angeles.

Then I use as.Date to convert character to date.

t <- as.Date(key$DATE[1], format = "%d%b%Y")
[1] "2004-01-05"

But when I use as.POSIXct(t), it returns me:

 > as.POSIXct(t)
[1] "2004-01-04 16:00:00 PST"
 > as.POSIXlt(t)
[1] "2004-01-05 UTC"

I tried several methods mentioned on website, but the result didn't change:

t <- as.Date(key$DATE[1], format = "%d%b%Y", 'PST')
t <- as.Date(key$DATE[1], format = "%d%b%Y", 'EST')
t <- as.Date(key$DATE[1], format = "%d%b%Y", tz="America/New_York")
t <- as.Date(keyi$DATE[1], format = "%d%b%Y", tz="America/Los_Angeles")
as.POSIXct(t, tz = "America/Los_Angeles")
as.POSIXct(t, tz = "America/New_York")

I want to know: what could I do so when I use as.POSIXct(t), it would return me "2004-01-05 PST" or any other timezone.

I am thinking because the Date is originally stored as character, so it wouldn't remember its original timezone, right?

I do get

as.Date(as.POSIXct(t))
> "2004-01-05"

But why would as.POSIXct(t) return the previous result? Because I also have other data files and I would get "2004-01-05 PST" using as.POSIXct(t).

Thank you!

like image 460
yuan yuan Avatar asked Sep 13 '25 20:09

yuan yuan


1 Answers

Your as.POSIXlt(t) shows that as.Date is using GMT by default. But as.POSIXct uses local time by default, so there is an unwanted conversion. But you can fix this.

strptime has a tz argument to specify the base time zone. This worked for me:

t = strptime(key$DATE[1], format = "%d%b%Y", tz= "America/Los_Angeles")
as.POSIXct(t)
[1] "2004-01-05 PST"

Warning: What does and does not work as a value for tz seems to be rather odd.

like image 184
G5W Avatar answered Sep 15 '25 09:09

G5W