I have written a simple code to check if the time difference between 2 date timestamps is more than 7 days, which comes to 604,800 seconds.
If the time in seconds is more than 604,800 then it should print "Relax you have time!!!"
Please find my code below:
import time, datetime, sys, os
start_time = time.time()
from datetime import datetime, timedelta, date
from dateutil.parser import *
datetime1="2018-07-13 03:30:00"
datetime2="2018-07-20 04:30:00"
datetime2=datetime.strptime(datetime2, "%Y-%m-%d %H:%M:%S").date() # this is to convert it into a datetime object
datetime1=datetime.strptime(datetime1, "%Y-%m-%d %H:%M:%S").date() # this is to convert it into a datetime object
difference1 =(datetime2-datetime1).total_seconds()
print("the difference in seconds is "+str(difference1))
if difference1 > 604800: #if the difference is more than 7 days, relax , else start preparing
print("Relax you have time!!!")
else:
print("You need to start preparing!!!!!")
Problem:
The code somehow calculates the time in seconds to be more than 604800 only if I change the "datetime2" to "2018-07-21" which means that it is calculating the difference in rounded-off days and not seconds and then simply converting the rounded-off days into seconds, giving the incorrect answer.
For example, in the above code, since "datetime2" is in reality away from "datetime1" by more than 604,800 seconds(to be precise it is 608,400 seconds away), the output should be "Relax you have time!!!", but we get a different output.
What have I done to solve this?
Till now I have looked at similar questions:
How do I check the difference, in seconds, between two dates? (did not work for me as I got TypeError: an integer is required (got type datetime.date))
and
Time difference in seconds (as a floating point) (this caters to only very tiny time differences and does not capture a scenario when user enters timestamps himself)
and
How to calculate the time interval between two time strings (this is what I have done in my code, but it does not work as expected)
Can you please suggest the problem in my code?
UPDATE: Thanks to #Tim Peters for pointing out that .date() discards the hours,mins and seconds.
I only needed to discard .date() for it to work correctly.
In this case the issue is that you create two datetime.datetime objects with strptime and immediately truncate them to datetime.date objects, which don't have the time components (hours, minutes, seconds, microseconds, tzinfo), so you get two calendar dates which are exactly 7 days apart.
You can fix your original code like this:
from datetime import datetime, timedelta
datetime1 = "2018-07-13 03:30:00"
datetime2 = "2018-07-20 04:30:00"
# The following creates two datetime.datetime objects
datetime2 = datetime.strptime(datetime2, "%Y-%m-%d %H:%M:%S")
datetime1 = datetime.strptime(datetime1, "%Y-%m-%d %H:%M:%S")
difference1 =(datetime2-datetime1).total_seconds()
print("the difference in seconds is "+str(difference1))
# if the difference is more than 7 days, relax , else start preparing
if difference1 > 604800:
print("Relax you have time!!!")
else:
print("You need to start preparing!!!!!")
But one additional thing to note is that datetime.timedelta objects can be directly compared, so you do not need to calculate the number of seconds, so you can change that part to avoid the "number of seconds" calculation (and your intention is clearer):
difference1 = datetime2 - datetime1
# if the difference is more than 7 days, relax , else start preparing
if difference1 > timedelta(days=7):
I imagine that in reality you are not constructing the datetime.datetime objects from string literals as you have in this example, but in case you are, I would also note that you can directly construct those literals as well, so with that refactoring in place, here's how I would have written your example:
from datetime import datetime, timedelta
# The following creates two datetime.datetime objects
datetime1 = datetime(2018, 7, 13, 3, 30)
datetime2 = datetime(2018, 7, 20, 4, 30)
difference1 = datetime2 - datetime1
# if the difference is more than 7 days, relax , else start preparing
if difference1 > timedelta(days=7):
print("Relax you have time!!!")
else:
print("You need to start preparing!!!!!")
Related
My code is the following:
date = datetime.datetime.now()- datetime.datetime.now()
print date
h, m , s = str(date).split(':')
When I print h the result is:
-1 day, 23
How do I get only the hour (the 23) from the substract using datetime?
Thanks.
If you subtract the current date from a past date, you would get a negative timedelta value.
You can get the seconds with td.seconds and corresponding hour value via just dividing by 3600.
from datetime import datetime
import time
date1 = datetime.now()
time.sleep(3)
date2 = datetime.now()
# timedelta object
td = date2 - date1
print(td.days, td.seconds // 3600, td.seconds)
# 0 0 3
You're not too far off but you should just ask your question as opposed to a question with a "real scenario" later as those are often two very different questions. That way you get an answer to your actual question.
All that said, rather than going through a lot of hoop-jumping with splitting the datetime object, assigning it to a variable which you then later use look for what you need in, it's better to just know what DateTime can do since that can be such a common part of your coding. You would also do well to look at timedelta (which is part of datetime) and if you use pandas, timestamp.
from datetime import datetime
date = datetime.now()
print(date)
print(date.hour)
I can get you the hour of datetime.datetime.now()
You could try indexing a list of a string of datetime.datetime.now():
print(list(str(datetime.datetime.now()))[11] + list(str(datetime.datetime.now()))[12])
Output (in my case when tested):
09
Hope I am of help!
The question in the title seems to be familiar as I could see lot of example blog posts and SO posts. However, I couldn't find a question similar to the issue I am facing. I have a netcdf file in which variable time has a single data value 10643385. The unit of this time variable is minutes since 2000-01-01 00:00:00 which is different from many examples I found on the internet.I am also aware of the fact that actual value of time is 27-03-2020 05:45. My query is that how do I get this epoch value int to the date time format like `27-03-2020 05:45'. Here is the sample code I have been trying which results in the reference datetime rather than actual datetime of the file:-
print(datetime.datetime.fromtimestamp(int(epoch_time_value)).strftime('%Y-%m-%d %H:%M:%S'))
The above single line of code result in 1970-05-04 09:59:45. Can some one help me to get the correct date.
import datetime
t = datetime.datetime(2000, 1, 1) + datetime.timedelta(minutes=10643385)
outputs
datetime.datetime(2020, 3, 27, 5, 45)
Python epoch time is in seconds, so we must first convert this to seconds by multiplying by 60.
Python epoch time starts on 1, Jan, 1970. Since netcdf starts on 2000-01-01, we must adjust by adding the amount of seconds from 1970 to 2000 (which happens to be 946684800).
Putting these together we get:
>>> import datetime
>>> epoch_time_value = 10643385
>>> _epoch_time_value = epoch_time_value * 60 + 946684800
>>> print(datetime.datetime.fromtimestamp(int(_epoch_time_value)).strftime('%Y-%m-%d %H:%M:%S'))
2020-03-26 22:45:00
Then, there may be some shift (possibly +/- 12 hours) based on timezone, so make sure the timezones in your calculations are synced when you do this!
I have 2 times stored in separate strings in the form of H:M I need to get the difference between these two and be able to tell how much minutes it equals to. I was trying datetime and timedelta, but I'm only a beginner and I don't really understand how that works. I'm getting attribute errors everytime.
So I have a and b times, and I have to get their difference in minutes.
E.G. if a = 14:08 and b= 14:50 the difference should be 42
How do I do that in python in the simplest way possible? also, in what formats do I need to use for each step?
I assume the difference is 42, not 4 (since there are 42 minutes between 14:08 and 14:50).
If the times always contains of a 5 character length string, than it's reasonably easy.
time1 = '14:08'
time2 = '15:03'
hours = int(time2[:2]) - int(time1[:2])
mins = int(time2[3:]) - int(time1[3:])
print(hours)
print(mins)
print(hours * 60 + mins)
Prints:
1
-5
55
hours will be the integer value of the left two digits [:1] subtraction of the second and first time
minutes will be the integer value of the right two digits [3:] subtraction of the second and first time
This prints 55 ... with your values it prints out 42 (the above example is to show it also works when moving over a whole hour.
You can use datetime.strptime
also the difference is 42 not 4 50-8==42 I assume that was a typo
from datetime import datetime
a,b = "14:08", "14:50"
#convert to datetime
time_a = datetime.strptime(a, "%H:%M")
time_b = datetime.strptime(b, "%H:%M")
#get timedelta from the difference of the two datetimes
delta = time_b - time_a
#get the minutes elapsed
minutes = (delta.seconds//60)%60
print(minutes)
#42
You can get the difference between the datetime.timedelta objects created from the given time strings a and b by subtracting the former from the latter, and use the total_seconds method to obtain the time interval in seconds, with which you can convert to minutes by dividing it by 60:
from datetime import timedelta
from operator import sub
sub(*(timedelta(**dict(zip(('hours', 'minutes'), map(int, t.split(':'))))) for t in (b, a))).total_seconds() // 60
So that given a = '29:50' and b = '30:08', this returns:
18.0
Hello I am using the daytime module in python 3.3 to takeaway two times like this:
time_format = '%H:%M:%S'
total_time = datetime.strptime(time_left_system, time_format) - datetime.strptime(time_entered_system, time_format)
how would i convert this into seconds so i could print it like this?: 60 mph
Thanks
You are going to want to use the timedelta type from the datetime module, timedelta.total_seconds() will give you the time elapsed in seconds. you already have a timedelta by subtracting one datetime from the other, so you are set for the next step.From there I don't know how you are converting it to mph, probably you are measuring against a fixed distance, just like people on the race track calculate with chronometers given the seconds a car took in a set track distance, but since you don't give the info on how you convert it I can't help you on that part.
I was working on code to generate the time for an entire day with 30 second intervals. I tried using DT.datetime and DT.time but I always end up with either a datetime value or a timedelta value like (0,2970). Can someone please tell me how to do this.
So I need a list that has data like:
[00:00:00]
[00:00:01]
[00:00:02]
till [23:59:59] and needed to compare it against a datetime value like 6/23/2011 6:38:00 AM.
Thanks!
Is there a reason you want to use datetimes instead of just 3 for loops counting up? Similarly, do you want to do something fancy or do you want to just compare against the time? If you don't need to account for leap seconds or anything like that, just do it the easy way.
import datetime
now = datetime.datetime.now()
for h in xrange(24):
for m in xrange(60):
for s in xrange(60):
time_string = '%02d:%02d:%02d' % (h,m,s)
if time_string == now.strftime('%H:%m:%S'):
print 'you found it! %s' % time_string
Can you give any more info about why you are doing this? It seems like you would be much much better off parsing the datetimes or using strftime to get what you need instead of looping through 60*60*24 times.
There's a great answer on how to get a list of incremental values for seconds for a 24-hour day. I reused a part of it.
Note 1. I'm not sure how you're thinking of comparing time with datetime. Assuming that you're just going to compare the time part and extracting that.
Note 2. The time.strptime call expects a 12-hour AM/PM-based time, as in your example. Its result is then passed to time.strftime that returns a 24-hour-based time.
Here's what I think you're looking for:
my_time = '6/23/2011 6:38:00 AM' # time you defined
from datetime import datetime, timedelta
from time import strftime, strptime
now = datetime(2013, 1, 1, 0, 0, 0)
last = datetime(2013, 1, 1, 23, 59, 59)
delta = timedelta(seconds=1)
times = []
while now <= last:
times.append(now.strftime('%H:%M:%S'))
now += delta
twenty_four_hour_based_time = strftime('%H:%M:%S', strptime(my_time, '%m/%d/%Y %I:%M:%S %p'))
twenty_four_hour_based_time in times # returns True