【问题标题】:Date issue while reading/writing csv files读取/写入 csv 文件时的日期问题
【发布时间】:2018-02-10 08:55:18
【问题描述】:

在将具有 IST 时区日期时间列的 .csv 文件加载到 RStudio 时,它会将其转换为 UTC 语言环境(-5:30)。因此我的子集比较检查没有给出确切的结果。例如。

csv 文件中的原始字符串:

> coilid$StartTime[1:5]
[1] "06/01/2017 00:29:10" "06/01/2017 01:19:19" "06/01/2017 02:09:31" "06/01/2017 03:05:08"
[5] "06/01/2017 03:48:51"

使用lubridate 加载:

lub_date = mdy_hms(coilid$StartTime[1:5])
> lub_date
[1] "2017-06-01 00:29:10 UTC" "2017-06-01 01:19:19 UTC" "2017-06-01 02:09:31 UTC" "2017-06-01 03:05:08 UTC"
[5] "2017-06-01 03:48:51 UTC"

字符串应该被读取为 IST 日期。这是默认的 UTC

> lub_date[1] > '2017-06-01 05:58:00'
[1] TRUE
> lub_date[1] > '2017-06-01 05:59:59'
[1] FALSE

因此添加了tz

lub_date_ist = mdy_hms(coilid$StartTime[1:5], tz = 'Asia/Calcutta')
> lub_date_ist
[1] "2017-06-01 00:29:10 IST" "2017-06-01 01:19:19 IST" "2017-06-01 02:09:31 IST" "2017-06-01 03:05:08 IST"
[5] "2017-06-01 03:48:51 IST"
> lub_date_ist[1] > '2017-06-01 00:29:59'
[1] FALSE
> lub_date_ist[1] > '2017-06-01 00:29:00'
[1] TRUE

现在的问题是,当我将其作为 data.table 保存到 csv 文件中并再次读取时,数据会损坏。

fwrite(data.table(lub_date_ist), file = paste0(path_loc, 'xxx.csv'))
fread(file = paste0(path_loc, 'xxx.csv'))
              V1 V2  V3
1: 2017-05-31T18 59 10Z
2: 2017-05-31T19 49 19Z
3: 2017-05-31T20 39 31Z
4: 2017-05-31T21 35 08Z
5: 2017-05-31T22 18 51Z

【问题讨论】:

  • 我建议您将日期存储为 UTC 时间。让您的消费者担心转换到他自己的时区。
  • @TimBiegeleisen 我是消费者。我将一个非常大的文件按月拆分,然后我因此丢失了数据点
  • 关键是您必须以UTC格式维护(读/写)文件中的数据。读取数据后,将其转换为所需的时区。

标签: r datetime


【解决方案1】:

这个想法是write/maintainfile/databaseUTC格式的日期/时间。以locale 格式存储日期/时间既困难又容易出错。特别是在应用DST 的时区。

实现它的步骤非常简单。在写入文件之前将日期/时间转换为UTC 格式。同样,以UTC 格式读取它,然后将其转换为语言环境时区。 with_tz 的使用对于将日期/时间转换为另一个时区非常重要。

请允许我用来自 OP 的数据来演示它。

library(lubridate)
coild <-  read.table(text = 'Sl Time
1 "06/01/2017 00:29:10" 
2 "06/01/2017 01:19:19"
3 "06/01/2017 02:09:31"
4 "06/01/2017 03:05:08"
5  "06/01/2017 03:48:51"', header = T, stringsAsFactors = F)

# The time is in IST format
coild$Time <- mdy_hms(coild$Time, tz="Asia/Calcutta")
[1] "2017-06-01 00:29:10 IST" "2017-06-01 01:19:19 IST" "2017-06-01 02:09:31 IST" 
[4] "2017-06-01 03:05:08 IST" "2017-06-01 03:48:51 IST"

# Convert it to "UTC" just before writing to file
fwrite(data.table(with_tz(coild$Time, tzone = "UTC")), file = 'xxx.csv')

# Read and convert it date/time in UTC format
DT <- fread(file = 'xxx.csv', sep = " ", colClasses=c("POSIXt"))
# Date is in UTC format
readTime <- parse_date_time(DT$V1, "%Y-%m-%d %H:%M:%S%z")

# Change date/time in IST 
with_tz(readTime, tzone = "Asia/Calcutta")

[1] "2017-06-01 00:29:10 IST" "2017-06-01 01:19:19 IST" "2017-06-01 02:09:31 IST"
[4] "2017-06-01 03:05:08 IST" "2017-06-01 03:48:51 IST"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2017-10-16
    相关资源
    最近更新 更多