简体   繁体   English

将格式“星期一,年时间上午/下午”的日期字符串转换为 R 中的 POSIXlt 格式?

[英]Convert Date String in Format "Mon Day, Year Time am/pm" to POSIXlt format in R?

I'm trying to convert a string to a date time.我正在尝试将字符串转换为日期时间。 I can't even get R to recognize and format the month though.我什至无法让 R 识别和格式化月份。

Here's a sample of the date formatting:这是日期格式的示例:

> for(i in sample_times){print(i)}
[1] "Aug 17, 2015 08:00 am"
[1] "Aug 15, 2015 12:06 am"
[1] "Jun 19, 2013 05:54 pm"
[1] "Aug 23, 2015 07:16 pm"
[1] "Aug 13, 2015 11:04 pm"
[1] "May 28, 2015 04:00 pm"
[1] "Jul 27, 2014 11:00 pm"
[1] "Aug 18, 2015 02:46 pm"
[1] "Aug 19, 2015 05:06 am"
[1] "Aug 25, 2015 07:27 pm"
[1] "Mar 12, 2014 10:14 am"
[1] "Aug 15, 2015 01:08 pm"
[1] "Aug 14, 2015 12:05 am"
[1] "Aug 18, 2015 11:07 am"
[1] "Aug 22, 2015 10:07 am"
[1] "Aug 24, 2015 12:38 pm"
[1] "Aug 21, 2015 08:17 pm"
[1] "Aug 23, 2015 08:34 pm"
[1] "Jun 11, 2015 09:44 pm"
[1] "Aug 23, 2015 01:54 pm"

Just calling strptime fails.只是调用strptime失败。 Returns NAs .返回NAs

Here's an example of what I tried, just to get the month out:这是我尝试过的一个例子,只是为了得到这个月:

strptime(x = tolower(substr(sample_times, 0, 3)), format = "%b")

This returns NA for every value, even though tolower(substr(sample_times, 0, 3)) returns lower case month abbreviations这将为每个值返回NA ,即使tolower(substr(sample_times, 0, 3))返回小写月份缩写

> tolower(substr(sample_times, 0, 3))
 [1] "aug" "aug" "jun" "aug" "aug" "may" "jul" "aug" "aug" "aug" "mar" "aug" "aug" "aug" "aug" "aug" "aug" "aug" "jun" "aug"

How do I convert my strings of dates to POSIXlt format?如何将日期字符串转换为POSIXlt格式? Sorry if this is a newb question: just getting started with time formatting in R.抱歉,如果这是一个新手问题:刚刚开始使用 R 中的时间格式。

You will want to use the format "%b %d, %Y %I:%M %p" in as.POSIXlt()您将需要在as.POSIXlt()使用格式"%b %d, %Y %I:%M %p"

  • %b for the abbreviated month (in the current locale) %b表示月份的缩写(在当前语言环境中)
  • %d for the day %d当天
  • %Y for the full four-digit year %Y表示完整的四位数年份
  • %I for the hour (when using %p aka am/pm) %I一小时(使用%p aka am/pm 时)
  • %M for the minutes %M分钟
  • %p for am/pm %p代表上午/下午

So for a POSIXlt date-time, you can do所以对于 POSIXlt 日期时间,你可以做

(x <- as.POSIXlt("Aug 19, 2015 07:09 am", format = "%b %d, %Y %I:%M %p"))
# [1] "2015-08-19 07:09:00 PDT"

As mentioned in the comments, you must have created the entire POSIX object in order to extract its parts (well, to formally extract them anyway).如评论中所述,您必须创建整个 POSIX 对象才能提取其部分(好吧,无论如何都要正式提取它们)。

months(x)
# [1] "August"
months(x, abbreviate = TRUE)
# [1] "Aug"

Additionally, in order to use strptime() , you must plan on creating the entire date-time object as you cannot just create a month and have it classed as such.此外,为了使用strptime() ,您必须计划创建整个日期时间对象,因为您不能只创建一个月份并将其归类为这样。 See help(strptime) and help(as.POSIXlt) for more.有关更多信息,请参阅help(strptime)help(as.POSIXlt)

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

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