can you tell me how can I calculate difference between 2 dates and get a result in minutes.
For exmpl. : date1 - 2016/07/13, 14:25:00
date2 - 2016/07/14, 10:00:00
If my format Is maybe different from format that python use(while I was searching for answer I saw a several formats) feel free to adapt it.
import datetime
from datetime import timedelta
def date(dd,vd,dp,vp):
datetimeFormat = '%Y/%m/%d %H:%M:%S'
time1 = ('{0} {1}'.format(dd,vd))
time2 = ('{0} {1}'.format(dp,vp))
timedelta = datetime.datetime.strptime(time2, datetimeFormat) - datetime.datetime.strptime(time1,datetimeFormat)
print (timedelta)
def main():
date1,time1='2016/07/13','14:25:00'
date2,time2='2016/07/14','10:00:00'
date(date1,time1,date2,time2)
if name=='main':
main()
If you compile it you will get something like 19hrs which is incorrect. Also I need result in minutes.
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!
I'm trying to convert strings into a date time object given the hours minutes seconds and milliseconds, so I can find the difference in time between the two strings. If there is a better way to do this please let me know, that'd be great.
the format of the date time object looks like this:
But when I tried subtracting two strings converted into date time objects the result wasn't correct. for example:
from datetime import datetime
format = '%H:%M:%S:%f'
x = '12:51:11:153'
time1 = datetime.strptime(x, format)
y = '13:51:11:153'
time2 = datetime.strptime(y, format)
difference = time2 - time1
print(difference)
"The print" = 0:00:00
Am I missing something for the format, or is there a special method to subtract datetime objects from each other? Also, is there an easier way to do this?
I think your solution is right. I can't reproduce that. This is my code and the output if I run it.
from datetime import datetime
import time
format = '%H:%M:%S:%f'
time1 = datetime.strptime("12:51:11:153", format)
time2 = datetime.strptime("13:51:11:153", format)
print((time2-time1).total_seconds())
--> 3600.0 seconds (type is float)
type(time2-time1) --> <class 'datetime.timedelta'>
time2-time1 --> datetime.timedelta(seconds=3600)
I have a time from five minutes ago, using datetime.time.now() and I need to know what the time would be if I subtracted that time from the current time.
Try 1 - Didn't Work:
from datetime import datetime, timedelta
time1 = datetime.now()
time2 = datetime.now() + timedelta(minutes=5)
print(time1 - time2)
This gave me "-1 day, 23:54:59.999987".
Try 2 - Worked, but is there a better way?:
time1 = datetime.now()
time2 = datetime.now() + timedelta(minutes=5)
print(str(time1 - time2).split(',')[1])
This gave me the desired result, but is there a method besides string manipulation?
You wanted to take an advice how to use a time object?
Well, if you want to specify a format of string representation of your time, just use strftime
Example below:
from datetime import datetime, timedelta
time1 = datetime.now()
time2 = datetime.now() + timedelta(minutes=5)
print((time1 - time2).strftime('%H:%M:%S'))
Assuming you want the time 5 minutes ago, you can use timedelta without any string manipulation:
five_min_ago = datetime.datetime.now() - datetime.timedelta(minutes = 5)
I have been thinking to do a sleep function where it sleeps until a certain date is called. My idea was based of date such as : 2019-01-20 12:00:00.
I haven't really figured out how to start to solve this problem. My idea was something similar such as
if there is a date given:
time.sleep(until the date and time)
So the question is how can I possibly be able to sleep until a certain time given in a value of 2019-01-20 12:00:00?
Easy, calculate how long it is, and sleep the time.
You can calculate how long it takes until your wakeup time is reached and sleep for the delta time.
Python can calculate with time intervals. If you subtract one timestamp from another, then you get a datetime.timedelta:
import datetime
import time
target = datetime.datetime(2019,1,20,12,0,0)
now = datetime.datetime.now()
delta = target - now
if delta > datetime.timedelta(0):
print('will sleep: %s' % delta)
time.sleep(delta.total_seconds())
print('just woke up')
of course, you can put that in a function:
import datetime
import time
target = datetime.datetime(2019,1,20,12,0,0)
def sleep_until(target):
now = datetime.datetime.now()
delta = target - now
if delta > datetime.timedelta(0):
time.sleep(delta.total_seconds())
return True
sleep_until(target)
You can check the return value: only if it slept, it returns True.
BTW: it's OK, to use a date in the past as target. This will generate a negative number of seconds. Sleeping a negative value will just not sleep.
if your time is a string, use this:
target = datetime.datetime.strptime('20.1.2019 20:00:00', '%d.%m.%Y %H:%M:%s')
or
target = datetime.datetime.strptime('2019-1-20 20:00:00', '%Y-%m-%d %H:%M:%s')
I did your problem in an efficient way:
import time, datetime
# given_date --> Your target time and date
dur = time.mktime(datetime.datetime.strptime(given_date, "%d-%b-%y %H:%M:%S").timetuple()) - time.time()
time.sleep(dur)
you mean something like this:
from time import sleep
from datetime import datetime
x = datetime.datetime.strptime('2019-01-20 12:00:00', '%Y-%m-%d %H:%M:%S')
y = datetime.now()
sleep((max(x,y) - min(x,y)).seconds)
You can use a while loop.
import datetime
_theday="01/01/2019"
while datetime.today() != _theday:
some stuff
I have data in the format as follows:
12/07/2018 23:00
12/07/2018 24:00
13/07/2018 1:00
and wanted to know if there exists a module in python that can change the 12/07/2018 24:00 to 13/07/2018 0:00
This should cover all cases for you assuming your dateformat string is static:
from datetime import datetime, timedelta
def fix_time(time_string):
if '24:00' in time_string: # Does time_string contain silly format
_date, _ = time_string.split() # Ignore time part since it will default to 00:00
calendar_date= datetime.strptime(_date, '%d/%m/%Y')
corrected_time = calendar_date + timedelta(days=1) # Add one day to get correct date
time_string = corrected_time.strftime('%d/%m/%Y %H:%M') # Convert back to str
return time_string
Sample output:
fix_time('31/12/2018 24:00')>'01/01/2019 00:00'
Code could be made more concise but this should be a good start point.