Archive for Timestamp

From this year to next with Python’s Arrow

Date/time done (almost) right

Anyone who has dealt with timezones in their software knows how much of a nightmare it can be. Anyone who has used Python for time handling will also find out that it’s a bit of a minefield. Since we’re almost in 2017, I thought I’d (belatedly) add to the Arrow hype train. Arrow offers a more Python-like experience when writing code that deals with time or timezones. It’s simple but concise*.

The code

As always, a demo is better than a thousand words.
Hopefully the code doesn’t need much explanation. We call now() if we want a local time arrow instance. now(‘%timezone%’) if we want the same in a different timezone. humanize() is a very cool sweetener that translates the arrow object into a more human readable format:

Here’s what we’d get as output:

Search and find instance

A nice little touch is the ability to grab a time from a string. The given example from the docs shows this off better than I could:
found_time = arrow.get('June was born in May 1980', 'MMMM YYYY')

Arrow will correctly extract “May 1980” based on the pattern and ignore “June”. There’s more over at the API docs.

Unfortunately this awesome library won’t stop me from writing 2016 everywhere for the next few weeks but for everything else it does the job.

* As with all timezone libs, they made a few mistakes that will draw criticism (some dodgy naming and the overly ambitious “get()”)