-2

I am developing an application in python where I need to calculate time elapsed and take appropriate action. I have two times as by default provided and current. I want compare the difference with some other time which is provided in string format.

I have tried following:

d1 = datetime.datetime(2015, 1, 21, 9, 54, 54, 340000)
print d1
d2 = datetime.datetime.now()
print d2
print d2 - d1
d3 =datetime.datetime.strptime("22:17:46.476000","%H:%M:%S.%f")
print d3

Output of the above program is :

2015-01-21 09:54:54.340000
2015-01-21 22:28:45.070000
12:33:50.730000
1900-01-01 22:17:46.476000

Here time difference is' 12:33:50.730000' and I want to compare it with '22:17:46.476000' which is string.

As I tried to convert string '22:17:46.476000' to time I got year as 1990. I want only time as '22:17:46.476000'. So I can compare these two time using timedelta.

How to get rid of year 1990-01-01. I want only '22:17:46.476000'.

I tried using time as time.strptime("22:17:46.476000","%H:%M:%S.%f") but it give output as time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=22, tm_min=17, tm_sec=46, tm_wday=0, tm_yday=1, tm_isdst=-1)

Thanks

ajay_t
  • 2,347
  • 7
  • 37
  • 62
  • to calculate the elapsed time correctly, you also need to take into account the local timezone. In particular, you should *not* substruct from `datetime.now()` value -- it is often an error, see [Find if 24 hrs have passed between datetimes - Python](http://stackoverflow.com/a/26313848/4279). – jfs Jan 22 '15 at 03:30

4 Answers4

1

As it stands, you are comparing two fundamentally different grandeurs.

When you subtract one Datetime object from another you get a "timedelta" object - that is a period of time, which can be expressed in days, hours, seconds, or whatever time unit.

Datetime objects on the other hand mark an specific point in time. When you parse the time-only string to a Datetime, since no year, month or day is specified, they get the default values of 1900-01-01.

So, since the value you want to compare the interval with is a time interval, not an specific point in time, that is what you should have on the other hand of the comparison.

The easiest way to do that from where you are is indeed to subtract, from your parsed object, the midnight of 1900-01-01 - and then you have a "timedelta" object, with just that duration. However, note that this is a hack, and as soon as the time interval you need to parse against is larger than 24h it will break (strptime certainly won't parse "30:15:..." as the 6th hour of 1901-01-02)

So, you'd better break apart and build a timedelta object from scratch for your string:

hour, min, sec = "22:17:46.476000".split(":")
d3 = datetime.timedelta(hours=int(hour), minutes=int(minutes), seconds=float(sec))
jsbueno
  • 99,910
  • 10
  • 151
  • 209
0

Given a datetime d3, you could obtain the time (without the date) using the time method:

>>> d3.time()
datetime.time(22, 17, 46, 476000)

You could then compare this time with d2.time():

>>> d2.time() > d3.time()
False

Alternatively, you could use combine to build a datetime out of d2's date and d3's time:

import datetime as DT
d1 = DT.datetime(2015, 1, 21, 9, 54, 54, 340000)
d2 = DT.datetime.now()
d3 = DT.datetime.strptime("22:17:46.476000","%H:%M:%S.%f")
d3 = DT.datetime.combine(d2.date(), d3.time())
print(d3)
# 2015-01-21 22:17:46.476000

You can then compare the two datetimes: d2 and d3. For example:

>>> d2 < d3 
True

>>> (d3-d2).total_seconds()
36664.503375
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • I upvoted this. Whoever downvoted it doesn't understand the [datetime module](https://docs.python.org/2/library/datetime.html). – Oliver W. Jan 21 '15 at 17:14
  • This answer has serious logic problems. the O.P. is asking about comparing time intervals - and parsing his comparison string as a datetime ant picking only the time part is obviously flawed. This might work, by chance, up to the point where his interval is >= 24h. – jsbueno Jan 21 '15 at 17:21
  • 1
    The OP asks, *"I want only time as '22:17:46.476000'. So I can compare these two time using timedelta."*. This implies that `'22:17:46.476000'` is a string representation of a time, not a timedelta. – unutbu Jan 21 '15 at 17:25
  • 1
    What you are saying does not even start to make sense. If the O.P. where interested in the day time, as a timestamp, he would not be subtracting two arbitrary timestamps to start with. Still, it would be the only way a kind of answer like this could apply. You still won't be able to compare datetime.time objects with timedeltas. – jsbueno Jan 21 '15 at 17:30
  • 2
    Ok - I admit what you are trying makes some sense in the wording context the O.P. is providing - but the O.P. is clearly confused by the datetime/timestamps concepts, as I try to clarify. – jsbueno Jan 21 '15 at 17:31
  • Suppose the OP has an application that prints the time of an event to a file. Now he wants to parse that time and compare it with the current time. If he knows that both times refer to the current day, then he truly is working with times, not timedeltas. I'm taking his question at face value. – unutbu Jan 21 '15 at 17:35
  • In that case, maybe the question would not start with """I am developing an application ... where I need to calculate time **elapsed** """ – jsbueno Jan 21 '15 at 18:00
0

The difference between two datetimes is a duration represented as a datetime.timedelta and not a datetime, so you can't format it using strftime.

Instead of using strptime to parse your value for d3, you should construct a datetime.timedelta directly. See the documentation for its constructor.

If you really need to parse d3 from a string, then you can either do the parsing yourself or use the python-dateutil package.

b4hand
  • 9,550
  • 4
  • 44
  • 49
0

If I understand you correctly, 22:17:46.476000 doesn't represent a time but a time delta (because you want to compare it to another time delta).

If so, what you really need is to construct a datetime.timedelta object from your string. Unfortunately, it looks like there is no built-in way to do it, however, here you may find some recipes.

Community
  • 1
  • 1
urim
  • 591
  • 4
  • 13