I cannot maintain the format of a date received from a dataframe

Asked

Viewed 57 times

2

I have a dataframe with a date string and another time column:

inserir a descrição da imagem aqui

And I want to concatenate the date with the time to stay in the string format "2016-12-25T08:38:00"

Initially I was trying this way:

datainicial=vpnsessions2[1,3]
View(datainicial)
horainicial=vpnsessions2[1,4]
View(horainicial)
dataehora=paste(datainicial,horainicial,sep="T")

But the result I get is:

17160T31080

After researching I found that the hour part is in seconds, and the date part I’m not sure, but I think it’s in days.

I managed to solve the hour by doing the following:

td <- seconds_to_period(horainicial)
dataehorain=paste(datainicial,sprintf('%02d:%02d:%02d', td@hour, minute(td), second(td)),sep="T")
View(dataehorain)

But the result is still not satisfactory:

17160T08:38:00

The time already appears well but the date does not.

I’ve tried several ways to try to get the date right, but I’m not getting it.

View image with code and values: https://snag.gy/koJca2.jpg

  • 2

    Just a hint: instead of putting a link with an image of the code, it is better to [Edit] the question and add the code to it (as text, not as image). See more details in this answer.

  • A better title for this question is: "how to add a number of days to a date"

1 answer

4


You’re right. The date is the number of days since the "Unix season". To get the date in the format you want:

as.Date("1970-01-01", format = "%Y-%m-%d") + 17160
[1] "2016-12-25"
  • If you do it that way, I’ll make the following mistake:

  • 1

    > dataehorain=Paste(as.Date(start date, format = "%Y-%m-%d") + 17160,sprintf('%02d:%02d:%02d', td@hour, minute(td), Second(td)),Sep="T") Error in as.Date.(start date, format = "%Y-%m-%d") : do not know how to Convert 'start date' to class "Date"

  • 1

    > as. Date(starting date, format = "%Y-%m-%d") Error in as.Date.default(starting date, format = "%Y-%m-%d") : do not know how to Convert 'starting date' to class "Date"

  • what the result of dput(datainicial)?

  • 1

    > dput(starting date) Structure(list(Starting date = Structure(17160, class = "Date")), . Names = "Datastart", Row.Names = c(NA, -1L), class = c("tbl_df", "tbl", "data.frame"))

  • and what the result of dput(horainicial)?

  • > dput(initial time) Structure(31080, class = c("hms", "difftime"), Units = "secs")

  • experiment paste(datainicial$DataInicioSessao, sprintf('%02d:%02d:%02d', td@hour, minute(td), second(td)),sep="T")

  • That’s right!!! That’s how it works. Thanks =)

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.