简体   繁体   English

如果时间在 12 小时和 24 小时时间之间混合,如何转换字符日期时间?

[英]How to convert character date time if time mixed between 12 hour and 24 hour time?

I have a large number of data that I read from various .csv files (using read_csv).我从各种 .csv 文件(使用 read_csv)中读取了大量数据。 The Datetime column is read in the files is read as a class character.在文件中读取的日期时间列被读取为类字符。 I need to convert this character column into the actual date time (and check for duplicates) for plotting purposes.我需要将此字符列转换为实际日期时间(并检查重复项)以进行绘图。 This gets interesting because the date isn't consistently in 12 hour or 24 hour format.这很有趣,因为日期并非始终采用 12 小时或 24 小时格式。 The time zone isn't consistent either, but I think I have that bit working correctly.时区也不一致,但我认为我可以正常工作。

I am relatively new to R and will take kindly to any positive suggestions.我对 R 比较陌生,并且会接受任何积极的建议。

This is how I am trying to do it presently:这就是我目前正在尝试这样做的方式:

# Add time zone information:
    # Some data uses 12-hour clock:
    if (sum(grep("AM", Data$Date))||sum(grep("PM", Data$Date))>0){
      if (Time_Zone == "Eastern Daylight Time"){
        Data$Date_Formatted <- as.POSIXct(Data$Date, "%m/%d/%Y %H:%M:%S", tz = "America/New_York")
        Data$Date_Formatted2 <- as.POSIXlt(Data$Date, "%m/%d/%Y %H:%M:%S", tz = "America/New_York")
      }
      else if (Time_Zone == "Central Daylight Time" || Time_Zone == "Central Standard Time") {
        Data$Date_Formatted <- as.POSIXct(Data$Date, "%m/%d/%Y %H:%M:%S", tz = "America/Chicago")
        Data$Date_Formatted2 <- as.POSIXlt(Data$Date, "%m/%d/%Y %H:%M:%S", tz = "America/Chicago")
      }
    }
    # Other data uses a 24-hour clock:
    else{
      if (Time_Zone == "Eastern Daylight Time"){
        Data$Date_Formatted <- as.POSIXct(Data$Date, "%m/%d/%Y %k", tz = "America/New_York")
        Data$Date_Formatted2 <- as.POSIXlt(Data$Date, "%m/%d/%Y %k", tz = "America/New_York")
      }
      else if (Time_Zone == "Central Daylight Time" || Time_Zone == "Central Standard Time") {
        Data$Date_Formatted <- as.POSIXct(Data$Date, "%m/%d/%Y %k", tz = "America/Chicago")
        Data$Date_Formatted2 <- as.POSIXlt(Data$Date, "%m/%d/%Y %k", tz = "America/Chicago")
      }
    }

I am not sure what the difference is between POSIXct and POSIXlt and found another thread that used both... so I did... I don't think that is necessary though.我不确定 POSIXct 和 POSIXlt 之间有什么区别,并找到了另一个同时使用两者的线程......所以我做到了......不过我认为这没有必要。

The 12-hour solution seems to be working just fine, but the 24-hour format must still be incorrect. 12 小时的解决方案似乎工作得很好,但 24 小时的格式肯定仍然不正确。

Try lubridate , it is a very robust package for dates and times:试试lubridate ,它是一个非常强大的日期和时间包:

library(lubridate)

ymd_hms(c("2019-01-20 10:25:00 PM", "2019-01-20 22:25:00"))
[1] "2019-01-20 22:25:00 UTC" "2019-01-20 22:25:00 UTC"

Check ?ymd_hms for more options.检查?ymd_hms以获取更多选项。

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

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