简体   繁体   中英

issue convert date variable from character to data.frame or data.frame to character

I'm extracting excel file to have multiple values in character including dates. From excel I take date_1. date_2 i get it from postgresql using dbgetquery which is always data.frame.

date_1 = "2017-05-22"
class(date_1)    # this is "character"
date_2 = "2017-05-20"
class(date_2)   # this is "data.frame"

days <- difftime(as.Date(date_1), as.Date(date_2), units = "days")
print(days)

calculate_age = julian(as.Date(date_1), as.Date(date_2))
print(calculate_age)

I'm getting below 2 error.

1. "Error in as.Date.default(date_2) : 
  do not know how to convert 'date_2' to class “Date”" 

2. Error in UseMethod("julian") : 
  no applicable method for 'julian' applied to an object of class "character"

Anyone please suggest. I tried many. but no help. Also I'm new to R and Postgresql.

You have a good foundation, but your as.Date has not specified what date format you are supplying. By specifying that the date strings are 'yyyy-mm-dd', days is calculated using the difftime( ) function.

date_1 = "2017-05-22"
date_2 = "2017-05-20"

days <- difftime(as.Date(date_1,format="%Y-%m-%d"),
                 as.Date(date_2,format="%Y-%m-%d"),
                 units = "days")

print(days)
Time difference of 2 days

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM