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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With