473,789 Members | 2,806 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Datetime utility functions

I was just writing some code which did date/time manipulations, and I
found that the Python 2.3 datetime module does not supply a number of
fairly basic functions. I understand the reasoning (the datetime
module provides a set of datatypes, and doesn't attempt to get into
the murky waters of date algorithms) but as these things can be quite
tricky to get right, I was wondering if anyone has already implemented
any date algorithms, or alternatively if I'd missed some easy way of
doing what I'm after.

My specific requirements were:

1. Get the last day of the month contatining a given date(time). I
really was surprised to find this one missing, as it seems to me that
the datetime module must know what the last day for each month is, so
exposing it wouldn't have been hard.

2. Add a number of months to a date. This is messy, as there are
options (what is one month after 31st Jan). The trouble is that the
calculation, while simple, is tricky to get right (month is 1-based,
so off-by-1 errors are easy to make, and divmod isn't as useful as
you'd first think).

Other "nice to have" functions which I didn't need for this program,
but which I have found useful in the past, are

- Round a date(time) to a {year,month,day ,quarter,week,. ..} Or
truncate. Or (occasionally) chop to the next higher boundary
(ceiling).
- Calculate the number of {years,months,d ays,...} between two dates.
(Which is more or less the equivalent of rounding a timedelta).

These latter two aren't very well defined right now, because I have no
immediate use case.

In the absence of anything else, I'll probably write a "date
utilities" module for myself at some point. But I'd hate to be
reinventing the wheel.

Paul.
Jul 18 '05 #1
14 6438

"Paul Moore" <pa********@ato sorigin.com> wrote in message
news:18******** *************** ***@posting.goo gle.com...
I was just writing some code which did date/time manipulations, and I
found that the Python 2.3 datetime module does not supply a number of
fairly basic functions. I understand the reasoning (the datetime
module provides a set of datatypes, and doesn't attempt to get into
the murky waters of date algorithms) but as these things can be quite
tricky to get right, I was wondering if anyone has already implemented
any date algorithms, or alternatively if I'd missed some easy way of
doing what I'm after.

My specific requirements were:

1. Get the last day of the month contatining a given date(time). I
really was surprised to find this one missing, as it seems to me that
the datetime module must know what the last day for each month is, so
exposing it wouldn't have been hard.
I'm kind of surprised to see that it's missing, too.
2. Add a number of months to a date. This is messy, as there are
options (what is one month after 31st Jan). The trouble is that the
calculation, while simple, is tricky to get right (month is 1-based,
so off-by-1 errors are easy to make, and divmod isn't as useful as
you'd first think).
That's application dependent. If a bond, for example, has interest
payable on the 30th of the month, you probably want the 30th,
except in February you want the last day of the month. However,
the contract may specify something else. And in no case do you
want the date to suddenly change to the 28th because you went
through February.
Other "nice to have" functions which I didn't need for this program,
but which I have found useful in the past, are

- Round a date(time) to a {year,month,day ,quarter,week,. ..} Or
truncate. Or (occasionally) chop to the next higher boundary
(ceiling).
- Calculate the number of {years,months,d ays,...} between two dates.
(Which is more or less the equivalent of rounding a timedelta).

These latter two aren't very well defined right now, because I have no
immediate use case.
Most of these don't have well defined, globally useful use cases.
It's heavily application dependent what you want out of these.
In the absence of anything else, I'll probably write a "date
utilities" module for myself at some point. But I'd hate to be
reinventing the wheel.
There's a very well regarded date module out there in the
Vaults of Parnassus. The name escapes me at the moment,
but a bit of spelunking through the Vaults will turn up several
date routines that may do what you want.

John Roth

Paul.

Jul 18 '05 #2
"John Roth" <ne********@jhr othjr.com> writes:
"Paul Moore" <pa********@ato sorigin.com> wrote in message
news:18******** *************** ***@posting.goo gle.com...
1. Get the last day of the month contatining a given date(time). I
really was surprised to find this one missing, as it seems to me that
the datetime module must know what the last day for each month is, so
exposing it wouldn't have been hard.


I'm kind of surprised to see that it's missing, too.


The best solution I could find was

def month_end(dt):
# Get the next month
y, m = dt.year, dt.month
if m == 12:
y += 1
m = 1
else:
m += 1

# Use replace to cater for both datetime and date types. This
# leaves the time component of a datetime unchanged - it's
# arguable whether this is the right thing.

return dt.replace(year =y, month=m, day=1) - datetime.timede lta(days=1)

It's not hard - but it's mildly tricky (I made a few false starts and
some silly off-by-one errors) and I'd much rather grab it from a
library than make the same mistakes next time I need it.
2. Add a number of months to a date. This is messy, as there are
options (what is one month after 31st Jan). The trouble is that the
calculation, while simple, is tricky to get right (month is 1-based,
so off-by-1 errors are easy to make, and divmod isn't as useful as
you'd first think).


That's application dependent.


True. But for "naive" use, a simple definition does. This is in line
with the datetime module's philosophy of not trying to cater for
"advanced" uses, but to provide something useful for straightforward
use. In this particular case, I'd argue that the obvious definition
(same day number N months on) where applicable, plus a well-documented
"reasonable " answer for the edge cases (eg, Jan 31 plus 1 month) is
useful. In practice, I suspect that 99% of cases involve adding a
number of months to either the first or the last of a month.
If a bond, for example, has interest payable on the 30th of the
month, you probably want the 30th, except in February you want the
last day of the month. However, the contract may specify something
else. And in no case do you want the date to suddenly change to the
28th because you went through February.


But that's not so much a case of adding a month, as a more complex
concept, a "repeating date". Nevertheless, I take your point.
In the absence of anything else, I'll probably write a "date
utilities" module for myself at some point. But I'd hate to be
reinventing the wheel.


There's a very well regarded date module out there in the
Vaults of Parnassus. The name escapes me at the moment,
but a bit of spelunking through the Vaults will turn up several
date routines that may do what you want.


I guess you're thinking of mxDateTime. I'm aware of this, and agree
that it's pretty comprehensive. I don't really know why I prefer not
to use it - partly it's just a case of reducing dependencies, also
there are already so many date types in my code (COM, cx_Oracle,
datetime) that I am reluctant to add another - there is already far
too much code devoted to converting representations ...

Thanks for the comments,
Paul.
--
This signature intentionally left blank
Jul 18 '05 #3

"Paul Moore" <pa********@ato sorigin.com> wrote in message
news:br******** **@yahoo.co.uk. ..
"John Roth" <ne********@jhr othjr.com> writes:
"Paul Moore" <pa********@ato sorigin.com> wrote in message
news:18******** *************** ***@posting.goo gle.com...
1. Get the last day of the month contatining a given date(time). I
really was surprised to find this one missing, as it seems to me that
the datetime module must know what the last day for each month is, so
exposing it wouldn't have been hard.


I'm kind of surprised to see that it's missing, too.


The best solution I could find was

def month_end(dt):
# Get the next month
y, m = dt.year, dt.month
if m == 12:
y += 1
m = 1
else:
m += 1


This looks incomplete. You could use this to get the sequential date
for the first of the next month, but you still have to subtract one day
and then print out the day.

# Use replace to cater for both datetime and date types. This
# leaves the time component of a datetime unchanged - it's
# arguable whether this is the right thing.

return dt.replace(year =y, month=m, day=1) - datetime.timede lta(days=1)

It's not hard - but it's mildly tricky (I made a few false starts and
some silly off-by-one errors) and I'd much rather grab it from a
library than make the same mistakes next time I need it.
As I said, I don't see any obvious reason why they wouldn't accept
a patch, if you want to submit it.
2. Add a number of months to a date. This is messy, as there are
options (what is one month after 31st Jan). The trouble is that the
calculation, while simple, is tricky to get right (month is 1-based,
so off-by-1 errors are easy to make, and divmod isn't as useful as
you'd first think).


That's application dependent.


True. But for "naive" use, a simple definition does. This is in line
with the datetime module's philosophy of not trying to cater for
"advanced" uses, but to provide something useful for straightforward
use. In this particular case, I'd argue that the obvious definition
(same day number N months on) where applicable, plus a well-documented
"reasonable " answer for the edge cases (eg, Jan 31 plus 1 month) is
useful. In practice, I suspect that 99% of cases involve adding a
number of months to either the first or the last of a month.


Except for the edge case I mention below, this is really too simple;
it's just add one to the month and keep the same date. Hardly worth
a method at all, especially if you have the "last day of month" method.
If a bond, for example, has interest payable on the 30th of the
month, you probably want the 30th, except in February you want the
last day of the month. However, the contract may specify something
else. And in no case do you want the date to suddenly change to the
28th because you went through February.


But that's not so much a case of adding a month, as a more complex
concept, a "repeating date". Nevertheless, I take your point.


Yes. When you've got something application dependent, they tend
not to put in "naive" definitions. What's a 'naive' definition for one
person
is simply wrong for another.

John Roth

Thanks for the comments,
Paul.
--

Jul 18 '05 #4
On 15 Sep 2003 08:07:07 -0700, rumours say that
pa********@atos origin.com (Paul Moore) might have written:

[about missing datetime functionality]
1. Get the last day of the month contatining a given date(time). I
really was surprised to find this one missing, as it seems to me that
the datetime module must know what the last day for each month is, so
exposing it wouldn't have been hard.


I would guess that the simple ones were not included just because they
are only a few lines each:

def end_of_month(a_ date):
year_inc, month_inc = divmod(a_date.m onth, 12)
return a_date.__class_ _(a_date.year+y ear_inc, 1+month_inc, 1) - \
datetime.timede lta(days=1)

def month_days(a_da te):
return end_of_month(a_ date).day

Examples:
end_of_month(da tetime.date.tod ay()) datetime.date(2 003, 9, 30) end_of_month(da tetime.datetime (1972,2,11)) datetime.dateti me(1972, 2, 29, 0, 0) month_days(date time.date.today ()) 30 end_of_month(da tetime.date(197 7,12,15))

datetime.date(1 977, 12, 31)

The add_months_to_d ate seems not that hard too, but I don't have a need
for one so far, so I haven't coded it :) My needs for datetime
intervals are usually of the 'one month start - another month end' kind,
so end_of_month is handy. If you do think these would be useful, feel
free to use them (or your own versions) for a patch.

Date / timedelta rounding / truncating to various units would have to
take account of many different rules, and none would be very generic
IMHO.
--
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.
Jul 18 '05 #5
On Mon, 15 Sep 2003 20:44:08 +0100, rumours say that Paul Moore
<pa********@ato sorigin.com> might have written:

[find the end of the month]
The best solution I could find was

def month_end(dt):
# Get the next month
y, m = dt.year, dt.month
if m == 12:
y += 1
m = 1
else:
m += 1

# Use replace to cater for both datetime and date types. This
# leaves the time component of a datetime unchanged - it's
# arguable whether this is the right thing.

return dt.replace(year =y, month=m, day=1) - datetime.timede lta(days=1)


I sent my own version without having seen your own --and mine might seem
obfuscated, compared to yours. Only a minor suggestion: don't use
dt.replace, use dt.__class__ instead, since you wouldn't want your
function to have side-effects (that is, don't destroy the actual object
that dt is bound to.)
--
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.
Jul 18 '05 #6
> I was just writing some code which did date/time manipulations, and I
found that the Python 2.3 datetime module does not supply a number of [...]

Your message arrived in the exact time.. :-)

Have a look at this:

http://article.gmane.org/gmane.comp.python.devel/52956

I'll publish it somewhere an announce here once I get the
time to do so.
My specific requirements were:

1. Get the last day of the month contatining a given date(time). I
really was surprised to find this one missing, as it seems to me that
the datetime module must know what the last day for each month is, so
exposing it wouldn't have been hard.


I don't understand this one. The last day of the month containing
a given datetime? A datetime is absolute, how would it be "contained"
in something else?

--
Gustavo Niemeyer
http://niemeyer.net

Jul 18 '05 #7
On Tue, 16 Sep 2003 11:28:58 -0400, rumours say that "Tim Peters"
<ti*****@comcas t.net> might have written:
[Christos TZOTZIOY Georgiou]
I sent my own version without having seen your own --and mine might
seem obfuscated, compared to yours. Only a minor suggestion: don't
use dt.replace, use dt.__class__ instead, since you wouldn't want your
function to have side-effects (that is, don't destroy the actual
object that dt is bound to.)


It's OK to use replace: datetime and date (also time and timedelta) objects
are immutable -- their values can't be changed after initialization. In
particular, x.replace() doesn't mutate x.


In some strange, unprecedented and inexplicable way, you are right...
<sigh> ...again :) RTFM-F virus not removed yet.

PS That bang thingie (!) in Ruby is pythonic.
--
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.
Jul 18 '05 #8
On Tue, Sep 16, 2003 at 05:19:50PM +0300, Christos TZOTZIOY Georgiou wrote:
....
I sent my own version without having seen your own --and mine might seem
obfuscated, compared to yours.


you both use the same indirect way of getting to the end of the month.
why not do what datetime.c does, like:

_days_in_month = [
0, # unused; this vector uses 1-based indexing */
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
]

def _is_leap_year(y ear):
return year % 4 == 0 and (year % 100 !=0 or year % 400 == 0)

def days_in_month(y ear, month):
if month == 2 and _is_leap_year(y ear):
return 29
else:
return _days_in_month[month]

def end_of_month(d) :
date(d.y, d.m, days_in_month(d .y, d.m))
--
groetjes, carel

Jul 18 '05 #9
Christos "TZOTZIOY" Georgiou <tz**@sil-tec.gr> writes:
I sent my own version without having seen your own --and mine might seem
obfuscated, compared to yours. Only a minor suggestion: don't use
dt.replace, use dt.__class__ instead, since you wouldn't want your
function to have side-effects (that is, don't destroy the actual object
that dt is bound to.)


dt.replace doesn't have side effects - it creates a new object. Also,
by using replace(), my version works with date, datetime, or
subclasses. Yours does too, but it sets the time component of a
datetime to zero. It's a matter of preference which behaviour is
"better", I guess.

Paul.
--
This signature intentionally left blank
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2350
by: Carlo Milanesi | last post by:
Let's say I want to write the following function, void f(const list<int> &l, const vector<int> &v) { cout << get_second(l) << '\n'; cout << get_second(v) << '\n'; cout << get_nth(l, 2) << '\n'; cout << get_nth(v, 2) << '\n'; } that prints the second and third (counting from zero) items of given
5
1882
by: Neil Zanella | last post by:
Hello, I need to access some user defined utility functions from within my ASP.NET pages. I wonder whether there is a way to do this. I do not want to use inheritance. I just want to be able to call some code contained in a .cs file (C# file) from within several ..aspx and .ascx page without having to rewrite the code in each such page. I would like to know how this can be accomplished, including how I can ensure that ASP.NET will find...
22
5358
by: John Salerno | last post by:
I might be missing something obvious here, but I decided to experiment with writing a program that involves a class, so I'm somewhat new to this in Python. Anyway, what is the best way to create a function (A) within a class that another function (B) can use? Function A is not something that an instance will ever call, so I figure it's a choice between static or class methods, but I don't know which one, or if this is even the right...
25
1870
by: John Salerno | last post by:
Just a quickie for today: Is it common (and also preferred, which are two different things!) to create a function that has the sole job of calling another function? Example: for fun and exercise, I'm creating a program that takes a quote and converts it into a cryptogram. Right now I have four functions: convert_quote -- the main function that starts it all make_code -- makes and returns the cryptogram make_set -- called from...
6
2253
by: Marco | last post by:
One of the things I like about C++ is that it doesn't force you to create fake "objects" in the OO sense. We had a debate at the office about the "right" way to encapsulate related utility functions (such as additional math functions). These would be pure functions with no state. 1) Create a class with all static functions 2) Use a named namespace
0
9666
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9511
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10200
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10142
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9021
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4093
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3703
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.