2017-12-27 385 views
0

如何將R中的日期轉換爲沒有破折號或斜線的字符串或沒有冒號的字母和時間。例如,我可以在R中獲得2017-12-07,但我需要201712071520在Weather API調用中使用。我怎樣才能做到這一點?有關參考請參閱下面的示例調用startDateTime和endDateTime。我想將我的日期轉換爲20171207格式,並在沒有冒號的情況下將其附加到固定時間(1520)。感謝您的幫助!需要將R中的日期和時間轉換爲此格式的「201712071520」,以獲取Weather API調用

我被告知這個問題之前已經被問到過,但其他例子正在將相反的字符串轉換爲R日期和時間。

這裏是我調用API的例子:

https://api.weather.com/v3/wx/hod/conditions/historical/point?pointType=nearest&geocode=39.86,-104.67&startDateTime=201712071520&endDateTime=201712071520&units=e&format=json&apiKey=yourApiKey

+0

德克,請告訴我,其確切的重複是因爲我無法找到它,感謝邁克爾 – Mike

+0

德克你的榜樣是如何將一個字符轉換成河,我希望做相反的並從R轉換爲字符串201712071520 – Mike

+0

已將評論移至答案。 –

回答

1

自評感動。

如果x爲R的"Date"類的,然後使用指定的format聲明:

x <- as.Date("2017-12-07") # test input 

format(x, "%Y%m%d1520") 
## [1] "201712071520" 

更多關於百分比代碼見?strptime

0

@G謝謝你的工作很棒!

0

這是一個更通用的解決方案。它應該是這樣的:

library(lubridate) 
    input_date = "2017-1-7" #intentionally taking different date to make it more generic 
    fixed_text = "1520" 
    input_date = ymd(input_date) 
    output_date = paste(year(input_date), sprintf(fmt = '%02d', month(input_date)), sprintf(fmt = '%02d', day(input_date)), fixed_text, sep = "") 
    print(output_date) 
相關問題