473,246 Members | 1,496 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,246 software developers and data experts.

Difference between two times (working ugly code, needs polish)

I have done what I wanted, but I think there must be a much better way.

Given two timestamps in the following format, I just want to figure
out how far apart they are (in days, seconds, whatever).

Format:

YYYY-MM-DD_MM:SS

Example:
2007-09-11_16:41
It seems to me that to do what I want, I need to convert a string into
a number (time.mktime()), such as this: 1189543487.0

Once I have that, I can just subtract one from the other and do
whatever I want. The ugly part is converting something like
2007-09-11_16:41 to the numeric equivalent.

Below is my code. Any suggestions?

Thanks in advance.
Here is what I have (works):

#runTimeStamp is the current time, set when the script begins execution
def recAge(lastUpdate, runTimeStamp):

import re

oneDay = 60 * 60 * 24

lastUpdate = re.sub(r'\D+', ',', lastUpdate)
lastUpdate = lastUpdate + ",0,0,0,0"
lastUpdate = [int(x) for x in lastUpdate.split(',')]
lastUpdate = time.mktime(tuple(lastUpdate))

runTimeStamp = re.sub(r'\D+', ',', runTimeStamp)
runTimeStamp = runTimeStamp + ",0,0,0,0"
runTimeStamp = [int(x) for x in runTimeStamp.split(',')]
runTimeStamp = time.mktime(tuple(runTimeStamp))

return (runTimeStamp - lastUpdate) / oneDay
Sep 11 '07 #1
7 1468
On 2007-09-11, Shawn Milochik <Sh***@Milochik.comwrote:
I have done what I wanted, but I think there must be a much better way.
See the strptime() function in either the time or the datetime
modules:

http://docs.python.org/lib/module-time.html
http://docs.python.org/lib/module-datetime.html

--
Grant Edwards grante Yow! Here we are in America
at ... when do we collect
visi.com unemployment?
Sep 11 '07 #2
Shawn Milochik a écrit :
I have done what I wanted, but I think there must be a much better way.

Given two timestamps in the following format, I just want to figure
out how far apart they are (in days, seconds, whatever).

Format:

YYYY-MM-DD_MM:SS

Example:
2007-09-11_16:41
It seems to me that to do what I want, I need to convert a string into
a number (time.mktime()), such as this: 1189543487.0

Once I have that, I can just subtract one from the other and do
whatever I want. The ugly part is converting something like
2007-09-11_16:41 to the numeric equivalent.

Below is my code. Any suggestions?
import time
print time.mktime(time.strptime("2007-09-11_16:41", '%Y-%m-%d_%H:%M'))
=1189521660.0

FWIW, you may also want to have a look at the datetime module, with
special attention to the timedelta class.

HTH
Sep 11 '07 #3
On 9/11/07, Grant Edwards <gr****@visi.comwrote:
On 2007-09-11, Shawn Milochik <Sh***@Milochik.comwrote:
I have done what I wanted, but I think there must be a much better way.

See the strptime() function in either the time or the datetime
modules:

http://docs.python.org/lib/module-time.html
http://docs.python.org/lib/module-datetime.html

Grant:

Thanks, this works, and is much shorter. Any further improvements, anyone?

def isOld(lastUpdate, runTimeStamp):

oneDay = 60 * 60 * 24

lastUpdate = time.mktime(time.strptime(lastUpdate, "%Y-%m-%d_%H:%M"))
runTimeStamp = time.mktime(time.strptime(runTimeStamp, "%Y-%m-%d_%H:%M"))

return (runTimeStamp - lastUpdate) / oneDay
Sep 11 '07 #4
Shawn Milochik wrote:
On 9/11/07, Grant Edwards <gr****@visi.comwrote:
>On 2007-09-11, Shawn Milochik <Sh***@Milochik.comwrote:
>>I have done what I wanted, but I think there must be a much better way.
See the strptime() function in either the time or the datetime
modules:

http://docs.python.org/lib/module-time.html
http://docs.python.org/lib/module-datetime.html


Grant:

Thanks, this works, and is much shorter. Any further improvements, anyone?

def isOld(lastUpdate, runTimeStamp):

oneDay = 60 * 60 * 24

lastUpdate = time.mktime(time.strptime(lastUpdate, "%Y-%m-%d_%H:%M"))
runTimeStamp = time.mktime(time.strptime(runTimeStamp, "%Y-%m-%d_%H:%M"))

return (runTimeStamp - lastUpdate) / oneDay
I suppose really oneDay should be a global (i.e. outside the function
definition). Apart from that it would be hard to improve on: obvious,
easy to read, in short - pythonic.

Are you concerned about daylight savings? That could certainly introduce
a whole new level of complexity into the problem. Let's hope not ...
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Sep 11 '07 #5
>
I suppose really oneDay should be a global (i.e. outside the function
definition). Apart from that it would be hard to improve on: obvious,
easy to read, in short - pythonic.

Are you concerned about daylight savings? That could certainly introduce
a whole new level of complexity into the problem. Let's hope not ...
I'm not concerned with DST; this is a script which checks my Ebay
auctions (I have some things for sale), and sends me e-mail whenever
someone bids. It's run by cron every half hour -- it keeps me from
compulsively checking my auctions. ^_^

In any case, DST isn't an issue because the same machine generates
both timestamps, and all I use it for is to stop displaying auctions
after they are 10 days old, so I don't get all my old crap filling up
the alert e-mail or skewing the total dollar amount for all active
auctions.

Thanks.
Shawn
Sep 12 '07 #6
On Sep 12, 1:31 am, "Shawn Milochik" <Sh...@Milochik.comwrote:
I suppose really oneDay should be a global (i.e. outside the function
definition). Apart from that it would be hard to improve on: obvious,
easy to read, in short - pythonic.
Are you concerned about daylight savings? That could certainly introduce
a whole new level of complexity into the problem. Let's hope not ...

I'm not concerned with DST; this is a script which checks my Ebay
auctions (I have some things for sale), and sends me e-mail whenever
someone bids. It's run by cron every half hour -- it keeps me from
compulsively checking my auctions. ^_^

In any case, DST isn't an issue because the same machine generates
both timestamps, and all I use it for is to stop displaying auctions
after they are 10 days old, so I don't get all my old crap filling up
the alert e-mail or skewing the total dollar amount for all active
auctions.

Thanks.
Shawn
Just to be picky - your function returns the number of days between
two dates, but it's called isOld, which looks like it should return a
boolean. i.e. it looks like it would be used as:

if not isOld(auctionDate, currentTime):
checkForBid()

rather than how I assume it is used:

if isOld(auctionDate, currentTime) <= 10:
checkForBid()

I'd call it daysDiff or something similar, or make it more specific so
that it works like the first block of code above:

ONEDAY = 60*60*24
OLDNESS_THRESHOLD = 10

def isOld(lastUpdate, runTimeStamp):
lastUpdate = time.mktime(time.strptime(lastUpdate, "%Y-%m-%d_%H:
%M"))
runTimeStamp = time.mktime(time.strptime(runTimeStamp, "%Y-%m-%d_
%H:%M"))
return (runTimeStamp - lastUpdate) / ONEDAY >= OLDNESS_THRESHOLD

if not isOld(auctionDate, currentTime):
checkForBid()

Iain

Sep 12 '07 #7
Just to be picky - your function returns the number of days between
two dates, but it's called isOld, which looks like it should return a
boolean. i.e. it looks like it would be used as:

if not isOld(auctionDate, currentTime):
checkForBid()

rather than how I assume it is used:

if isOld(auctionDate, currentTime) <= 10:
checkForBid()

I'd call it daysDiff or something similar, or make it more specific so
that it works like the first block of code above:
You're absolutely right; I started writing it with one purpose in mind
and changed it midstream. I actually renamed it yesterday to dayDiff.
;o)

Shawn
Sep 12 '07 #8

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

Similar topics

7
by: Philip Kofoed | last post by:
Greetings, I have a SQL server 2000 running on an english win2000 workstation. In a database I have a table where one varchar column is set to polish collation. Regional settings for the system...
23
by: gregf | last post by:
I have a paragraph of text pasted into a word document, it's in Polish, complete with polish characters. They show up just fine in word, but the program I use for web page programming, HomeSite,...
14
by: Steve McLellan | last post by:
Hi, Sorry to repost, but this is becoming aggravating, and causing me a lot of wasted time. I've got a reasonably large mixed C++ project, and after a number of builds (but not a constant...
1
by: tepperis | last post by:
hi, the DB2 v. 7 resides on a Z/OS mainframe. we want to support different languages with special local characters for one kind of information. if someone is using hungarian, the string may...
3
by: Kenneth McDonald | last post by:
Over the last couple of years, I've built a module called rex that lays on top of (and from the user's point of view, hides) the re module. rex offers the following advantages over re. *...
17
by: roN | last post by:
Hi, I'm creating a Website with divs and i do have some troubles, to make it looking the same way in Firefox and IE (tested with IE7). I checked it with the e3c validator and it says: " This...
9
by: HC | last post by:
Hello, all, I started out thinking my problems were elsewhere but as I have worked through this I have isolated my problem, currently, as a difference between MSDE and SQL Express 2005 (I'll just...
3
by: Steve | last post by:
I am trying to calculate elapsed travel times for flights. My plan is to enter the local departure time, the departure city and the local arrival time and city. These times would be standardised...
15
by: student4lifer | last post by:
Hello, I have 2 time fields dynamically generated in format "m/d/y H:m". Could someone show me a good function to calculate the time interval difference in minutes? I played with strtotime() but...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.