Remove timezone during POSIXlt Conversion in R

牧云@^-^@ 提交于 2019-12-23 12:52:42

问题


I have a column in my dataframe as datetime (factor) with the values as "15-10-2017 16:41:00".

I wanted this data to be converted as "2017-10-15 16:41:00". When i try to convert this, I'm getting the timezone also as output.

I tried using tz="", usetz=F but no use. Any suggestions ?

Code:

as.POSIXlt("15-10-2017 16:41:00",format = "%d-%m-%Y %H:%M:%S") [1] "2017-10-15 16:41:00 IST"


回答1:


From the help page of as.POSIXlt:

"" is the current time zone

which is the default.

That's why it does not work. You could remove the timezone information this way, and it will not show while printing:

my_datetime <- as.POSIXlt("15-10-2017 16:41:00",format = "%d-%m-%Y %H:%M:%S")
my_datetime$zone <- NULL
my_datetime

but I don't understand why you would want to do that. You should convert to GMT if you don't want to worry about the timezone. Also lubridate package has a nice force_tz function if you have to force some specific timezones.




回答2:


If you are ok storing the datetime as a character instead of as a POSIXlt, then you can use strftime():

my_datetime <- as.POSIXlt("15-10-2017 16:41:00",format = "%d-%m-%Y %H:%M:%S")
strftime(my_datetime)



回答3:


I do it like this:

strip.tz <- function(dt) {
  fmt <- "%Y-%m-%d %H:%M:%S"
  strptime(strftime(dt, format = fmt, tz=""), format = fmt, tz="UTC")
}

and you would use it like this:

my_datetime <- as.POSIXct("15-10-2017 16:41:00",format = "%d-%m-%Y %H:%M:%S")
strip.tz(my_datetime)


来源:https://stackoverflow.com/questions/44970127/remove-timezone-during-posixlt-conversion-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!