MoonPoint Support Logo

 

Shop Amazon Warehouse Deals - Deep Discounts on Open-box and Used ProductsAmazon Warehouse Deals



Advanced Search
January
Sun Mon Tue Wed Thu Fri Sat
         
15
           
2016
Months
Jan


Fri, Jan 15, 2016 10:44 pm

Determining the number of days from or to a given date with Python

If you wish to know how many days have passed since a given date, you can do so in Python using the datetime module. If I wanted to know the number of days from December 31, 2013 until today, I could use the code below, which shows 745 days have elapsed since that date:
$ python
Python 2.7.5 (default, Jun 24 2015, 00:41:19)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import date as D
>>> print (D.today() - D(2013, 12, 31)).days
745
>>> exit()
$

If, instead, I want to know the number of days that remain until a given date, a command such as the one below, which calculates the number of days from today until April 31, 2019, could be used.

>>> print (D(2019, 4, 30) - D.today()).days
1201

Of course, the calculations don't have to be from or to today, any arbitrary day can be selected as shown in the example below, which provides the number of days between January 1, 2016 and January 1, 2019

>>> print ( D(2019, 1, 31) - D(2016, 1, 31) ).days
1096

If you would prefer to get the result from the command line, aka shell prompt, with just one command line rather than through the Python interpreter's interactive mode, a command such as the following one could be used:

$ python -c "from datetime import date as D; print ( D(2019,1,31) - D(2016,1,31) ).days"
1096
$

[/languages/python] permanent link

Valid HTML 4.01 Transitional

Privacy Policy   Contact

Blosxom logo