How to understand strptime vs. strftime

The difference between Time and DateTime has to do with implementation. A large amount of the DateTime functionality comes from the Rails world and is an arbitrary date with time of day. It’s more of a calendar-based system. Time is measured as seconds since January 1, 1970 UTC and is time-zone agnostic. On some systems it is limited to values between 1901 and 2038, a limitation of how traditionally this value is stored as a signed 32-bit integer, but newer versions of Ruby can handle a much wider range, using a 64-bit value or BigNum as required.

In short, DateTime is what you get from a database in Rails where Time is what Ruby has traditionally used. If you’re working with values where dates are important and you want to know things like the end of the month or what day it’ll be six weeks ahead, use DateTime. If you’re just measuring elapsed time and don’t care about that, use Time. They’re easy to convert between if necessary.

Date on the other hand is just a calendar date and doesn’t have any associated times. You might want to use these where times are irrelevant.

strptime is short for “parse time” where strftime is for “formatting time”. That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification. I’ve rarely seen strptime used since DateTime.parse is usually good at picking up

Leave a Comment