My Profile Photo

Internet of Me by Jerad Acosta

A place to reference, recite, rinse and repeat my efforts, failures, thoughts and progress, delusions and regressions, but mostly a sandbox for whoever I am at the moment. Perhaps I'll occasionally enjoy the reminiscing with the castles or taking census of the endless games of tic-tac-toe etched in my box.

Python Dates and Times

Python Dates and Times

Dates and times can be stored in many different ways.
The offset from the Epoch is one of the most common nethods for storing dates and time.
The Epoch is January 1, 1970. The measurements is usually the numer of miliseconds since this date.

In Python you can get the current time since the epoch using the time module.

import time as tm

You can create a timestamp using the fromtimestamp() function on the datetime object

import datetime as dt
dtnow = dt.datetime.fromtimestamp(tm.time())
datetime.datetime(2016, 11, 2, 19, 12, 25, 640018)

The datetime object has attributes to get the representative hour, day, seconds, etc

datetime objects allow for simple math using time deltas.
This allows us to use a date and a time delta to find another date seperated by that delta.

Let’s find the date 100 days before today using the timedelta() function in the datetime library.

delta = dt.timedelta(days = 100)
today =
today - delta, 7, 25)

Here we see that 100 days before today - previously shown at 2016, 11, 2 - is 2016, 7, 25

We can also use conditionals as expected. Are timestamps equal to greater than less than etc, using are known conditional operators.
For example: Today is certainly greater than 100 days ago we just computed (when measuring time since the Jan 1 1970 epoch)

today > today-delta
comments powered by Disqus