1

Strptime function in R returns null values. I have a column in my dataset which has time in the foll format "2000" "1830" and so on.....

I am trying to give a time format to a column and get the date and time in the below specified format "%Y-%m-%d %H:%M:%S"

data$date <- strptime(data$date, '%Y-%m-%d %H:%M')

when I run the code I am getting NA's

zx8754
  • 52,746
  • 12
  • 114
  • 209
John
  • 11
  • 1

1 Answers1

2

It seems like you only have a time, not a date, is that correct? Also, there is no : between the hour and minutes in your data, but you did specify it in the format. Does this help?

strptime("2000", format = "%H%M")
strptime("1830", format = "%H%M")
Lennyy
  • 5,932
  • 2
  • 10
  • 23
  • Yes I don't have date. I have around 21 fields in the column with different times that needs to be changed but when I run this strptime("2000", format = "%H%M") strptime("1830", format = "%H%M") all 21 of them gets changed to the same value – John Apr 15 '19 at 12:28
  • Do you perhaps mean that today's date is added to those times? You could wrap the `strptime` function into `format(x, "%H:%M")` to only extract the time afterwards, like this: `format(strptime("1830", format = "%H%M"), "%H:%M")`, which gives `"18:30"` – Lennyy Apr 15 '19 at 12:32
  • No, what I mean is I have 21 fields with different times that needs to be changed to their corresponding values. so there are multiple times like "1830" "1930" "2000" and so on. So I need to give these 21 fields with different times a proper time format. Using this code strptime("2000", format = "%H%M") all 21 are getting changed to 20:00:00. – John Apr 15 '19 at 12:37
  • I see what you mean, you should replace the `"2000"` by your variable name. In case your dataframe is called `df` and the column is called `col`, should do: `strptime(df$col, format = "%H%M")` – Lennyy Apr 15 '19 at 12:41
  • strptime(df$col, format = "%H%M") this command works. I can see the results in the console but how to get the same result in the CSV? I'm very new to R sorry to bother you over and over again. – John Apr 15 '19 at 13:01
  • I understand you are new to R and SO, therefore, I'd like to invite you to take the StackOverFlow tour: https://stackoverflow.com/tour and read https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example to improve the way you can ask questions. I bring it up because comments are generally not meant for longer discussions, and for a new question it also generally considered good practice to at first search for related questions and then ask a new question only in case you can't find related questions. Nevertheless, a hint: take a look at the `write.csv()` function :) – Lennyy Apr 15 '19 at 13:39