[R] Query about use of format in strptime

Enrico Schumann es at enricoschumann.net
Mon Apr 11 09:55:41 CEST 2016

On Mon, 11 Apr 2016, Stefano Sofia <stefano.sofia at regione.marche.it> writes:

> Dear R-list users,
> I need to use strptime because I have to deal with date with hours and minutes.
> I read the manual for strptime and I also looked at many examples, but when I try to apply it to my code, I always encounter some problems.
> I try to change the default format, with no success. Why? How can I change the format?
> 1.
> init_day <- as.factor("2015-02-24-00-30")
> strptime(init_day, format="%Y-%m-%d-%H-%M")
> [1] "2015-02-24 00:30:00"
> It works, but why also seconds are shown if in format seconds are not specified?
> 2.
> init_day <- as.factor("2015-02-24-0-00")
> strptime(init_day, format="%Y-%m-%d-%H-%M")
> [1] "2015-02-24"
> Again, the specified format is not applied. Why?
> Thank you for your attention and your help
> Stefano

strptime creates a POSIXlt object, and the specified format
tells it how to interpret the string you pass in. (Your
factor is converted to character by strptime.)

If you want to have the POSIXlt object printed in a
particular way, use ?strftime or ?format.

  > format(strptime(init_day, format="%Y-%m-%d-%H-%M"), "%Y-%m-%d-%H-%M")
  ## [1] "2015-02-24-00-00"

Enrico Schumann
Lucerne, Switzerland

More information about the R-help mailing list