需要将R中的日期和时间转换为此格式的“201712071520”,以获取Weather API调用

问题描述:

如何将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

已将评论移至答案。 –

自评感动。

如果x为R的"Date"类的,然后使用指定的format声明:

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

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

更多关于百分比代码见?strptime

@G谢谢你的工作很棒!

这是一个更通用的解决方案。它应该是这样的:

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)