Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime since a given date to minutes [duplicate]

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

like image 947
user530476 Avatar asked Aug 28 '12 08:08

user530476


2 Answers

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.

like image 114
Martijn Pieters Avatar answered Oct 22 '22 06:10

Martijn Pieters


If you want the minutes of the delta between two dates, you can make a datetime.timedelta object by subtracting the two dates (see here), and then retrieve the minutes as shown in this question:

Convert a timedelta to days, hours and minutes

like image 30
Lior Avatar answered Oct 22 '22 08:10

Lior