rdatetimemutate

Converting a timestamp into a datetime in a dataframe in R


I have a dataframe where the original source uses a timestamp instead of a date/time. I want to mutate the df so that a new column is created for datetime. But when I try to do this, only the first row's timestamp is used (i.e., the datetime from the first row is in the new column for all of the rows).

Fairly simple code:

mightysat <- mightysat %>% mutate(datetime = as_datetime(timestamp))

But this is what my output looks like: output table

I'm sure I'm missing something ridiculously stupid, but have been pounding my head on this, and I can't go on to my next step until this is complete. If I have to, I'll do them all manually (it's fortunately not a huge data set), but really would like to make this work.

Thanks!


Solution

  • The anytime package can do this, either to local time (via function anytime) or to UTC (via function utctime). So try

    mightysat$datetime <- anytime::utctime(mightysat$Timestamp)
    

    and for example the first few values are

    > anytime::utctime(c(1668895203, 1668905643, 1668905998))
    [1] "2022-11-19 22:00:03 UTC" "2022-11-20 00:54:03 UTC" "2022-11-20 00:59:58 UTC"
    >