Working with dates and times in programming can be a painful test at times. In Python, there are some excellent libraries that help with all the pain, and recently I became aware of Pendulum. It is effectively are replacement for the standard datetime class and it has a number of improvements. Check out the documentation for further information.
Installation of the packages is straightforward with pip:
$ pip install pendulum
For example, some simple manipulations involving time zones:
import pendulum now = pendulum.now('Europe/Paris') # Changing timezone now.in_timezone('America/Toronto') # Default support for common datetime formats now.to_iso8601_string() # Shifting now.add(days=2)
Duration can be used as a replacement for the standard timedelta class:
dur = pendulum.duration(days=15) # More properties dur.weeks dur.hours # Handy methods dur.in_hours() 360 dur.in_words(locale='en_us') '2 weeks 1 day'
It also supports the definition of a period, i.e. a duration that is aware of the DateTime instances that created it. For example:
dt1 = pendulum.now() dt2 = dt1.add(days=3) # A period is the difference between 2 instances period = dt2 - dt1 period.in_weekdays() period.in_weekend_days() # A period is iterable for dt in period: print(dt)
Give it a go, and let me know what you think of it.