How Many Seconds Are There Till End Of Month?

Loading

(datetime.datetime(datetime.datetime.today().year, datetime.datetime.today().month, calendar.monthrange(datetime.datetime.today().year, datetime.datetime.today().month)[1]) - datetime.datetime.today()).total_seconds()

There's a log going on in that one liner. Let's break it down.

The two key Python modules we need to calculate the number of seconds till the end of year are datetime and calendar.

calendar.monthrange(year, month) returns a tuple. The tuple's second element is the number of days in the month.

We create two date objects:
date object 1: today
date object 2: the last day of the month

We subtract object 1 from object 2. Finally, we call .total_seconds() on the resultant object.

>>> import datetime
>>> import calendar
>>> (datetime.datetime(datetime.datetime.today().year, datetime.datetime.today().month, calendar.monthrange(datetime.datetime.today().year, datetime.datetime.today().month)[1]) - datetime.datetime.today()).total_seconds()
1290914.259939
>>> 

About the author

Sudheer is an entrepreneur and software developer. Get more from Sudheer on Twitter.


Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>. The supported tag styles are: <foo>, [foo].

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
By submitting this form, you accept the Mollom privacy policy.