Possible Duplicate:
Python datetime to Unix timestamp
Is there a way to convert a datetime
to int
, representing the minutes since, for example, January 2012, so that this int
can be modified, written to a database, compared and so on?
EDIT:
The server I am running this on uses Python 2.6.6
Subtracting two datetime.datetime
objects gives you a timedelta
object, which has a .total_seconds()
method (added in Python 2.7). Divide this by 60 and cast to int()
to get minutes since your reference date:
import datetime
january1st = datetime.datetime(2012, 01, 01)
timesince = datetime.datetime.now() - january1st
minutessince = int(timesince.total_seconds() / 60)
or in a python shell:
>>> import datetime
>>> january1st = datetime.datetime(2012, 01, 01)
>>> timesince = datetime.datetime.now() - january1st
>>> minutessince = int(timesince.total_seconds() / 60)
>>> minutessince
346208
For python 2.6 and earlier, you'll have to use the .days
and .seconds
attributes to calculate the minutes:
minutessince = timesince.days * 1440 + timesince.seconds // 60
which gives you an integer as well.