[讀書筆記r4ds]16.Dates and times

在線讀書:
R for data science
github地址: https://github.com/hadley/r4ds

16. Dates and Times

library(lubridate)

16.2 Creating date/times

3種date/times格式:

  • date. Tibbles print this as <date>.

  • time. Tibbles print this as <time>.

  • date-time. is a date plus a time: (typically to the nearest second). Tibbles print this as <dttm>.

You should always use the simplest possible data type that works for your needs.
today() ## date of today
now() ## date-time of now
3 種需要使用date/time的途徑荔仁;

  • From a string.
  • From individual date-time components.
  • From an existing date/time object.

16.2.1 From strings

通過y年戈钢,m月免都,d日的不同順序組合來創(chuàng)制

ymd("2017-01-31") ## 年月日
#> [1] "2017-01-31"
mdy("January 31st, 2017")## 月日年
#> [1] "2017-01-31"
dmy("31-Jan-2017") ## 日月年
#> [1] "2017-01-31"
ymd(20170131) ##也可以識別非字符串形式

也可以創(chuàng)制date-time

ymd_hms("2017-01-31 20:11:59")
#> [1] "2017-01-31 20:11:59 UTC"
mdy_hm("01/31/2017 08:01")
#> [1] "2017-01-31 08:01:00 UTC"

16.2.2 From individual components

對于分散在不同列中的組成部分使用
make_date() for dates, or make_datetime() for date-times:

flights %>% 
  select(year, month, day, hour, minute) %>% 
  mutate(departure = make_datetime(year, month, day, hour, minute))
#> # A tibble: 336,776 x 6
#>    year month   day  hour minute departure          
#>   <int> <int> <int> <dbl>  <dbl> <dttm>             
#> 1  2013     1     1     5     15 2013-01-01 05:15:00
#> 2  2013     1     1     5     29 2013-01-01 05:29:00
#> 3  2013     1     1     5     40 2013-01-01 05:40:00
#> 4  2013     1     1     5     45 2013-01-01 05:45:00
#> 5  2013     1     1     6      0 2013-01-01 06:00:00
#> 6  2013     1     1     5     58 2013-01-01 05:58:00
#> # … with 3.368e+05 more rows

-date-times in a numeric context (like in a histogram), 1 means 1 second, so a binwidth of 86400 means one day. For dates, 1 means 1 day.

16.2.3 From other types

  • as_datetime() #轉(zhuǎn)換date-time格式诉儒,
  • as_date() # 轉(zhuǎn)換為date格式剧罩。
  • “Unix Epoch”時間衔瓮,是從Epoch(1970年1月1日00:00:00 UTC)開始所經(jīng)過的秒數(shù)见擦,不考慮[閏秒]沼头。在大多數(shù)的[UNIX]系統(tǒng)中UNIX時間戳存儲為32位,這樣會引發(fā)2038年問題或Y2038解藻。If the offset is in seconds, use as_datetime(); if it’s in days, use as_date().
as_datetime(today())
#> [1] "2019-01-08 UTC"
as_date(now())
#> [1] "2019-01-08"
as_datetime(60 * 60 * 10)
#> [1] "1970-01-01 10:00:00 UTC"
as_date(365 * 10 + 2)
#> [1] "1980-01-01"

16.3 Date-time components

  • year() , month(), mday() (day of the month), yday() (day of the year), wday() (day of the week), hour(), minute(), and second().
  • month() and wday() 可以設(shè)置 label = TRUE參數(shù)老充,顯示月份或者星期幾的縮寫。設(shè)置abbr = FALSE 參數(shù)可以顯示全稱螟左。

16.3.2 Rounding 近似

  • floor_date() #round down (floor)往前
  • round_date() # 四舍五入
  • ceiling_date()# round up (ceiling)靠后

16.3.3 Setting components

  • 使用 <- 對date/time 進(jìn)行更改
  • update() # 對多個部分進(jìn)行修改啡浊。update(datetime, year = 2020, month = 2, mday = 2, hour = 2)
  • If values are too big, they will roll-over

16.4 Time spans

  • durations, 持續(xù)時間.
  • periods, 周期.
  • intervals, 起止時間.

16.4.1 Durations

  • 兩個時間相減 ## 產(chǎn)生的格式為difftime
  • as.duration()###轉(zhuǎn)換為duration格式。始終以秒為單位計算持續(xù)時間巷嚣,Larger units are created by converting minutes, hours, days, weeks, and years to seconds at the standard rate (60 seconds in a minute, 60 minutes in an hour, 24 hours in day, 7 days in a week, 365 days in a year).
  • dseconds() ##通過函數(shù)創(chuàng)制Duration 格式的時間,形式為dxxxs()
    dminutes() ##
    dhours()
    ddays()
    dweeks()
    dyears()
  • 時間間隔可以相加或相減 ##如果遇到閏年廷粒、夏令時等問題窘拯,結(jié)果會不同坝茎。

16.4.2 Periods 周期

以下函數(shù)將創(chuàng)制周期為單位的數(shù)據(jù)树枫,同類型數(shù)據(jù)可以相加減:
days() # 1天
seconds(15) ## 15s
minutes(10) ## 10min
hours(12) ## 12 hour
months()## 月
weeks() ## 周
years()## 年

16.4.3 Intervals

  • today() %--% next_year ### 以"%--%" 隔開兩個時間點,得到Interval 格式的數(shù)據(jù)景东。
  • pick the simplest data structure that solves your problem.
  • If you only care about physical time, use a duration;
  • if you need to add human times, use a period;
  • if you need to figure out how long a span is in human units, use an interval.
    image.png

    Figure 16.1 不同時間格式的計算操作規(guī)律.

16.5 Time zones

  • Sys.timezone() # 查看系統(tǒng)時區(qū)
  • lubridate always uses UTC. UTC (Coordinated Universal Time) is the standard time zone used by the scientific community and roughly equivalent to its predecessor GMT (Greenwich Mean Time).調(diào)世界時是以原子時秒長為基礎(chǔ)砂轻,在時刻上盡量接近于世界時的一種時間計量系統(tǒng)斤吐。
  • GMT(Greenwich Mean Time)——格林尼治標(biāo)準(zhǔn)時間
  • It does not have DST, which makes a convenient representation for computation. DTS是Daylight Saving Time的縮寫,稱為陽光節(jié)約時,在我國稱為夏時制,又稱夏令時,是一種為節(jié)約能源而人為調(diào)整地方時間的制度搔涝。
  • Operations that combine date-times, like c(), will often drop the time zone.

16.3.4 Exercises

  1. How does the distribution of flight times within a day change over the course of the year?
flights_dt %>% 
  mutate(dep_time=update(dep_time,year = 2020, month = 2, mday = 2)) %>% 
  ggplot(aes(dep_time))+geom_freqpoly(binwidth = 3600)
  1. Compare dep_time, sched_dep_time and dep_delay. Are they consistent? Explain your findings.
flights_dt %>% 
  mutate(delay=(dep_time-sched_dep_time)) %>% 
  select(tailnum,dep_time,sched_dep_time,dep_delay,delay) 
  1. Compare air_time with the duration between the departure and arrival. Explain your findings. (Hint: consider the location of the airport.)
flights %>% select(air_time,distance) %>% 
  ggplot(aes(distance,air_time))+geom_point()
  1. How does the average delay time change over the course of a day? Should you use dep_time or sched_dep_time? Why?
##
flights_dt %>% mutate(dep_time=update(dep_time,year=2013,month=1,mday=1))%>% 
  group_by(dep_time) %>% 
  summarise(mean=mean(dep_delay)) %>% 
  ggplot(aes(dep_time,mean))+geom_line()
flights_dt %>% mutate(sched_dep_time=update(sched_dep_time,year=2013,month=1,mday=1))%>% 
  group_by(sched_dep_time) %>% 
  summarise(mean_delay=mean(dep_delay)) %>% 
  ggplot(aes(sched_dep_time,mean_delay))+geom_point()+geom_smooth()
  1. On what day of the week should you leave if you want to minimise the chance of a delay?
flights_dt %>% mutate(weekday=wday(sched_dep_time)) %>% 
  group_by(weekday) %>% 
  summarise(mean=mean(dep_delay)) %>% 
  ggplot(aes(weekday,mean))+geom_line()
  1. What makes the distribution of diamonds$carat and flights$sched_dep_time similar?
    by human judgement
ggplot(diamonds,aes(carat))+geom_freqpoly()
sched_dep <- flights_dt %>% 
    mutate(minute = minute(sched_dep_time)) %>% 
    group_by(minute) %>% 
    summarise(
        avg_delay = mean(arr_delay, na.rm = TRUE),
        n = n())
ggplot(sched_dep, aes(minute, n)) +
    geom_line()
  1. Confirm my hypothesis that the early departures of flights in minutes 20-30 and 50-60 are caused by scheduled flights that leave early. Hint: create a binary variable that tells you whether or not a flight was delayed.
flights_dt %>% mutate(minute=minute(sched_dep_time),is=dep_delay<0) %>% 
  group_by(minute) %>% 
  summarise(ave_delay=mean(is),n=sum(is)/n()) %>% 
  ggplot(aes(minute,n))+geom_line()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末和措,一起剝皮案震驚了整個濱河市庄呈,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌派阱,老刑警劉巖诬留,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異贫母,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)腺劣,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來橘原,“玉大人籍铁,你說我怎么就攤上這事趾断。” “怎么了芋酌?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長隔嫡。 經(jīng)常有香客問我甸怕,道長腮恩,這世上最難降的妖魔是什么梢杭? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任秸滴,我火速辦了婚禮,結(jié)果婚禮上荡含,老公的妹妹穿的比我還像新娘咒唆。我一直安慰自己释液,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布误债。 她就那樣靜靜地躺著,像睡著了一般寝蹈。 火紅的嫁衣襯著肌膚如雪李命。 梳的紋絲不亂的頭發(fā)上箫老,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天,我揣著相機(jī)與錄音耍鬓,去河邊找鬼。 笑死牲蜀,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的各薇。 我是一名探鬼主播项贺,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼峭判,長吁一口氣:“原來是場噩夢啊……” “哼开缎!你這毒婦竟也來了林螃?” 一聲冷哼從身側(cè)響起奕删,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤疗认,失蹤者是張志新(化名)和其女友劉穎伏钠,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體谨设,經(jīng)...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年赴肚,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片誉券。...
    茶點故事閱讀 39,953評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖踊跟,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情鸥诽,我是刑警寧澤,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布决帖,位于F島的核電站,受9級特大地震影響蓖捶,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜俊鱼,卻給世界環(huán)境...
    茶點故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望并闲。 院中可真熱鬧,春花似錦帝火、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽九巡。三九已至图贸,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間疏日,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工沟优, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人净神。 一個月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓溉委,卻偏偏與公主長得像鹃唯,于是被迫代替她去往敵國和親瓣喊。 傳聞我的和親對象是個殘疾皇子坡慌,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,901評論 2 355

推薦閱讀更多精彩內(nèi)容

  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,454評論 0 13
  • By clicking to agree to this Schedule 2, which is hereby ...
    qaz0622閱讀 1,455評論 0 2
  • 疫中小城 文|思 山巒起伏洪橘,綠水漾波 白色小城安靜地躺臥 大地廝守承諾 云彩變幻的魔術(shù)師,刷子急切涂抹 萬千金屬光...
    思_zs912閱讀 282評論 0 1
  • 故惜酒 醉成莫泣他日別熄求, 陽關(guān)莫哀...
    無鯹鶴酒閱讀 204評論 0 1
  • 昨日逗概,同學(xué)群里轉(zhuǎn)發(fā)一條北外福建校友會的消息弟晚。原來我初中85歲的英語老師參加了校友會還被特別提及。作為北外50年代...
    流一盞燈閱讀 326評論 0 5