473,800 Members | 2,518 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: Writing elapsed time as a string

En Fri, 02 May 2008 16:13:41 -0300, Simon Pickles <si*******@goog lemail.comescri bió:
I'm sorry if this has been asked a thousand (million) times.

Is there a nifty pythonesque way to produce a string representing an
elapsed time period, in terms of years, months, days, hours, mins, seconds?

I am storing times in a MySQL db, and would love to be able to write the
time elapsed between accesses of certain data. These are in seconds
since the epoch, as produced by time.time()
Two options:

a) You can construct a datetime object with that info, using datetime.dateti me.fromtimestam p()
(note that the MySQLdb module already returns datetime objects for timestamp columns in MySQL).
If you substract two datetime objects, you get a timedelta object, which stores info as whole days, seconds (fraction of day) and microseconds (fraction of second). If you can live with years having exactly 365 days and months having exactly 30 days (or up to 35!):

def timedelta_str(t d):
def plural(n):
if n>1: return 's'
return ''
out = []
y, d = divmod(td.days, 365)
if y: out.append('%d year' % y + plural(y))
m, d = divmod(d, 30)
if m: out.append('%d month' % m + plural(m))
if d: out.append('%d day' % d + plural(d))
h, s = divmod(td.secon ds, 60*60)
if h: out.append('%d hour' % h + + plural(h))
m, s = divmod(s, 60)
if m: out.append('%d min' % m + plural(m))
if s: out.append('%d sec' % s + plural(s))
return ' '.join(out)

pyfrom datetime import datetime
pyd1 = datetime(1992, 5, 11, 8, 23, 8, 612)
pyd2 = datetime.now()
pyprint d1
1992-05-11 08:23:08.000612
pyprint d2
2008-05-08 09:21:53.592000
pyprint timedelta_str(d 2-d1)
16 years 1 day 58 mins 45 secs

or b) Use the dateutil package <http://labix.org/python-dateutil>
It is probable right in front of me in the docs but I am spinning off
into outer space (mentally!)
Nope... showing time intervals as years,months,da ys... isn't trivial, because there are many special cases, and sometimes legal issues too. It's impossible to make everyone happy in this topic.

--
Gabriel Genellina

Jun 27 '08 #1
0 1515

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

Similar topics

2
5162
by: Besta | last post by:
Hello all, I am having trouble creating a windows service with a timer. Everything seems to go ok but the elapsed event does not fire.Can anyone shed any light on this, may be something simple as I am new to this. Full code below : using System; using System.Collections; using System.ComponentModel;
4
13197
by: VB Programmer | last post by:
When I run my ASP.NET 2.0 web app on my dev machine it works perfect. When I precomile it to my web deployment project and then copy the debug files to my web server I get this problem when trying to login (obviously it's using ASPNETDB.mdf). Any ideas? Server Error in '/' Application. --------------------------------------------------------------------------------
4
11133
by: Liverpool fan | last post by:
I have a windows application written using VB .NET that encompasses a countdown timer modal dialog. The timer is a System.Timers.Timer with an interval of 1 second. AutoReset is not set so accepts the default of True. The Elapsed event handler updates the dialog box with how long before it will close, acting as a timer itself. The dialog has a time to close property which is checked every time the Elapsed event fires. The problem I have...
1
5255
by: Bill | last post by:
I have a large number of records that have an elapsed time in seconds for each one that I was to have a total time spent. I can sum them up with query easily enough but I need to be able to display this in a easier to read format. I was able to do that for individual records by multiplying the elapsed time by (1/24/60/60) and using hh:nn:ss for the format but can't for the total because it is greater than 24 hours. I need to be able to do...
12
16381
by: Spitfire | last post by:
I've a requirement to find the elapsed time between two function calls. I need to find the time elapsed accurate to 1 millisecond. The problem I'm facing right now is that, I'm using the 'time()' function call for the purpose and regardless of how many time I invoke the function within my program, I get the same output!!! For better clarity consider the code snippet below. ... start_time = time(NULL);
12
3311
by: pekka | last post by:
I'm trying to measure user input time with my Timer class object. It isn't as easy as I expected. When using std::cin between timer start and stop, I get zero elapsed time. For some unknown reason, the clock seems to stop ticking during execution of std::cin. Here's my code: #include <ctime> #include <iostream> #include <string>
0
1289
by: ravitunk | last post by:
hi all...i have a web service with a timer which has an Elapsed time of 1second(code should get executed for every second).....with the following code.....its running perfectly for the first time and has a problem during the next second...the code under "onelapsedtime" is getting executed..... public partial class Service1 : ServiceBase { Timer timer1 = new Timer(); SqlConnection cn = new...
0
165
by: M.-A. Lemburg | last post by:
On 2008-05-08 14:31, Gabriel Genellina wrote: Using mxDateTime that's pretty easy (using number of days): 3050:18:01:25.91 or, if you'd rather like to see things broken down as relative date/time diff (this is a calendar based diff): (+0008)-(+04)-(+07) (+18):(+04):(+41)
9
3319
by: Ross | last post by:
I'm a newbie at this, and have searched a lot but can't find something that seems appropriate for measuring a recurring elapsed time. Creating an object with: var mydate = new Date(); seems clear, as is creating a second: nowTime = new Date(); and getting a difference between the two. My quesiton is what if you have many, maybe thousands of intervals you wish to measure? Should I do: nowTime = new Date(); with every pass of a...
0
9550
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
10273
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
10250
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
10032
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...
0
9085
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
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4149
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
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2944
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.