简体   繁体   English

使用as.POSIXct用R转换日期

[英]Converting dates with R using as.POSIXct

I'm working with dates and R and I'm converting dates using the as.POSIXct function. 我正在使用日期和R,并且正在使用as.POSIXct函数转换日期。 I have a pretty good understanding of how to convert dates by just looking at the ?strptime docs. 我仅通过查看?strptime文档就对如何转换日期有了很好的理解。 However I'm confused about why this specific conversion doesn't work as expected (see below). 但是,我对为什么这种特定的转换无法按预期工作感到困惑(请参阅下文)。

date_string <- "03/11/2017, 3:14:32 pm"
as.POSIXct(date_string, format = "%m/%d/%Y, %H:%M:%S",tz="PST8PDT")

> [1] "2017-03-11 03:14:32 PST" 

I'm losing 12 hours of time with this conversion, I'm expecting this.. 我期望这样的转换会浪费12个小时的时间。

> [1] "2017-03-11 15:14:32 PST"

I've tried using '%r' with my formatting but that always gives me NA's? 我已经尝试过在格式中使用'%r',但这总是给我NA吗? Can somebody explain what R is doing here, and why it's not converting this date string as expected? 有人可以解释R在这里做什么,以及为什么它没有按预期方式转换此日期字符串?

Two mistakes: 两个错误:

  • you used %H where you want %I for the dreaded 12-hour format 您将%H用于您想要%I的可怕的12小时格式
  • you omitted %p to catch the "pm" marker 您省略了%p来捕捉“ pm”标记

With that corrected: 更正了以下内容:

R> date_string <- "03/11/2017, 3:14:32 pm"
R> as.POSIXct(date_string, format = "%m/%d/%Y, %I:%M:%S %p",tz="PST8PDT")
[1] "2017-03-11 15:14:32 PST"
R> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM