如何在 R 中使用 strptime() 保持午夜(00:00h)? [英] How can I keep midnight (00:00h) using strptime() in R?

查看:24
本文介绍了如何在 R 中使用 strptime() 保持午夜(00:00h)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框 df,它具有以下格式的日期因子变量:

I have a dataframe, df, which has factor variable for date in the following format:

2015-12-15 10:00:00
2015-12-19 12:00:00
2015-12-20 20:00:00

这是每小时的数据.在查看午夜 00:00:00 时会出现问题,因为它没有显示小时.它只是说:

It is hourly data. The problem arises when looking at midnight, 00:00:00, because it doesn't appear the hour. It just says:

21/12/2015

如您所见,它只表示日期,但缺少小时.所以我使用 strptime 转换为日期格式:

So as you see, it only says the day but it lacks the hour. So I use strptime to convert to a date format using:

df$date <- strptime(df$date,"%d/%m/%Y %H:%M")

除了午夜 00:00:00 的任何一天,它在所有小时和天都可以正常工作,它会返回:

It all works fine for all the hours and days except for any day at midnight, 00:00:00, which returns:

NA

我非常感谢一些帮助,因为我一直在查看 StackOverflow 和其他论坛中的以前的帖子,但我还没有设法找出解决这个特定问题的方法.

I'd really appreciate some help as I've been looking at previous posts in StackOverflow and other forums but I havent' managed to figure out the solution for this specific problem yet.

推荐答案

来自 R 的 strptime 文档(重点添加):

From R's strptime documentation (emphasis added):

格式

一个字符串.格式方法的默认值为%Y-%m-%d %H:%M:%S";如果任何元素的时间分量不是午夜,并且%Y-%m-%d"否则.如果设置了 options(digits.secs"),最多将打印指定的位数秒.

A character string. The default for the format methods is "%Y-%m-%d %H:%M:%S" if any element has a time component which is not midnight, and "%Y-%m-%d" otherwise. If options("digits.secs") is set, up to the specified number of digits will be printed for seconds.

所以信息还在,你只需要format把它和时间组件一起打印出来.

So the information is still there, you just need to format it to print it out with the time components.

> midnight <- strptime("2015-12-19 00:00:00","%Y-%m-%d %H:%M")
> midnight
[1] "2015-12-19 EST"
> format(midnight,"%Y/%m/%d %H:%M")
[1] "2015/12/19 00:00"

这篇关于如何在 R 中使用 strptime() 保持午夜(00:00h)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆