473,803 Members | 3,461 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
14 6442
Carel Fellinger <ca************ *@chello.nl> writes:
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:


Mainly because that seems even more like reinventing the wheel.
Writing code that already exists is something I dislike doing at the
best of times. Writing *tricky* code that already exists feels even
more unpleasant. (Yes, I know the leap year calculation isn't that
hard - but lots of people have got it wrong in the past...)

I guess that's my real issue. I know the datetime module already has
this information. But persuading it to tell me requires me to jump
through hoops, whereas reimplementing it feels like admitting defeat.

None of it's hard, though. I've spent more time on emails about the
issue than I'd ever need to spend in implementing anything :-)

Paul.
--
This signature intentionally left blank
Jul 18 '05 #11
On Tue, 16 Sep 2003 20:26:01 +0100, rumours say that Paul Moore
<pf******@yahoo .co.uk> might have written:

[I suggesting dt.__class__() instead of dt.replace()]
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.


You are right about dt.replace not having side-effects, just like some
anonymous<wink> major python contributor commented. Also .replace feels
"better" since it doesn't lose the time information.

PS ...but I still like my use of divmod() ;-)
--
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.
Jul 18 '05 #12
> > you both use the same indirect way of getting to the end of the month.
why not do what datetime.c does, like:


Mainly because that seems even more like reinventing the wheel.
Writing code that already exists is something I dislike doing at the

[...]

Why not using calendar.monthr ange()?

--
Gustavo Niemeyer
http://niemeyer.net

Jul 18 '05 #13
pa********@atos origin.com (Paul Moore) wrote in message news:<18******* *************** ****@posting.go ogle.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.

[description of needed functions]


I wrote a module just like that at my last job. Given a date object,
you could find the first or last day of the month, quarter, or year.
There were also functions to answer questions like "What was the date
5 months ago?" or "What date is the first Monday after October 8?"

Unfortunately, I don't have a copy of the source code here.
Jul 18 '05 #14
Try 'mxDateTime' available at

http://www.egenix.com/files/python/e...ownload-mxBASE

It most likely has what you are looking for.

Paul Moore wrote:
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 #15

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
1883
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
5361
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
1874
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
9703
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
10550
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10317
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
10295
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
10069
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7604
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5633
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3799
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2972
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.