String to time python in hours and minutes and calculate difference - python

I am taking time as input from the user in the HH:MM format. Let's say 00:00 and now I want to keep adding a minute to the time and make it 00:01, 00:02 and so on.
Also, I am taking two inputs form the user start_time and end_time as strings. How can I calculate the difference between the two times as well in minutes?
I am new to Python and any help would be appreciated!
I am using the below code:
#to calculate difference in time
time_diff = datetime.strptime(end_time, '%H:%M') - datetime.strptime(start_time, '%H:%M')
minutes = int(time_diff.total_seconds()/60)
print minutes
#to convert string to time format HH:MM
start_time = datetime.strptime(start_time, '%H:%M').time()
#to increment time by 1 minute
start_time = start_time + datetime.timedelta(minutes=1)
I am not able to increment the start_time using timedelta.

import datetime
time_diff = datetime.datetime.strptime(end_time, '%H:%M') - datetime.datetime.strptime(start_time, '%H:%M')
minutes = int(time_diff.total_seconds()/60)
print minutes
datetime is a class of the datetime module that has a classmethod called strptime. The nomenclature is a bit confusing, but this should work as you intend it to.
As for adding a time delta, you'll need store the start time as a datetime object in order to get that to work:
start_datetime = datetime.datetime.strptime(start_time, '%H:%M')
start_datetime = start_datetime + datetime.timedelta(minutes=1)
print start_datetime

First part of your question, you can use the datetime module:
from datetime import datetime as dt
from datetime import timedelta as td
UsrInput = '00:00'
fmtString = '%H:%M'
myTime = dt.strptime(UsrInput, fmtString)
increment = td(0,1)
for count in range(10):
myTime += increment
print (dt.strftime(myTime, fmtString))
Second part will also use datetime, as such:
from datetime import datetime as dt
from datetime import timedelta as td
start_time = '00:01'
end_time = '00:23'
fmtString = '%H:%M'
myStart = dt.strptime(start_time, fmtString)
myEnd = dt.strptime(end_time, fmtString)
difference = myEnd - myStart
print(td.strftime(difference, '%M')

Related

Python subsetting data by hour and minute, ignoring date

I have a list of image timestamps in the format '20121002_1639' ('%Y%m%d_%H%M')
I want to create a function that takes in a list of these timestamps and excludes images taken between
1500(3:00pm) and 1700 (5:00pm). However When I try to just parse the %H%M portion of the string, it automatically assigns those datetimes to the date 19000101_1500 and 19000101_1700. So I need to create objects which contain just hours and minutes but are not associated with a date.
The pseudo code would be something like this:
import datetime as dt
# example datetime string
datestrings = ['20121002_1639', '20111101_1229', '20160424_1502', '20170328_1100']
Start_time = dt.datetime.strptime('1500', '%H%M')
End_time = dt.datetime.strptime('1700', '%H%M')
good_times = []
for time in datestrings:
if dt.datetime.strptime(time[9:13], '%H%M') is between(Start_time, End_time):
continue
else:
good_times.append(time)
You may use only the time part from the datetime object, for that use the .time() method. So you don't need to parse only a part of the given string, parse all and then take it's time part too
datestrings = ['20121002_1639', '20111101_1229', '20160424_1502', '20170328_1100']
Start_time = dt.datetime.strptime('1500', '%H%M').time()
End_time = dt.datetime.strptime('1700', '%H%M').time()
good_times = []
for time in datestrings:
if not (Start_time <= dt.datetime.strptime(time, '%Y%m%d_%H%M').time() < End_time):
good_times.append(time)
print(good_times) # ['20111101_1229', '20170328_1100']
In fact you coud even do it with basic int comparisons
Start_time = 1500
End_time = 1700
for time in datestrings:
if not (Start_time <= int(time.split("_")[-1]) < End_time):
good_times.append(time)

Python comparing to different time values to get time delta in minutes

I am trying to get get the time delta i minutes from two different time values.
time1 = 2020-11-28T10:31:12Z
time2 = 2020-11-28T09:10:23.203+0000
Then i will make i condition: if time difference is bigger then x minutes, run code...
Anyone have a solution for that.
I have tried using datetime.datetime.strptime() but cant get them on same format.
Thanks
Using date parser to let it figure out the date format
Code
from dateutil.parser import parse
def time_difference(time1, time2):
# Parse strings into datetime objects
dt1 = parse(time1)
dt2 = parse(time2)
# Get timedelta object
c = dt1 - dt2
# Difference in minutes
return (c.total_seconds()/60)
Test
time1 = "2020-11-28T10:31:12Z"
time2 = "2020-11-28T09:10:23.203+0000"
print(time_difference(time1, time2))
# Output: 80.81328333333333
well assuming you don't need split seconds you could do something like that:
time1 = '2020-11-28T10:31:12Z'
time2 = '2020-11-28T09:10:23.203+0000'
import time
import datetime
def get_timestamp(time_str):
time_splited = time_str.split('T')
time_str_formatted = ' '.join([time_splited[0],time_splited[1][:8]])
return time.mktime(datetime.datetime.strptime(time_str_formatted,"%Y-%m-%d %H:%M:%S").timetuple())
print(get_timestamp(time1))
print(get_timestamp(time2))
reformatting both times to the same time format.
then your condition would look like:
if abs(get_timestamp(time1) -get_timestamp(time2) ) > x*60:
do_something(....)
The times are not uniform so you will have to make them the same to use strptime. For accuracy I prefer to convert to seconds then you can also at a later stage compare seconds, minutes or hours if you needed to.
import datetime
time1 = '2020-11-28T10:31:12Z'
time2 = '2020-11-28T09:10:23.203+0000'
def minutes_diff():
#Make the times uniform so you can then use strptime
date_time1 = datetime.datetime.strptime(time1[:-1], "%Y-%m-%dT%H:%M:%S")
date_time2 = datetime.datetime.strptime(time2[:-9], "%Y-%m-%dT%H:%M:%S")
#Convert to seconds for accuracy
a_timedelta = date_time1 - datetime.datetime(1900, 1, 1)
b_timedelta = date_time2 - datetime.datetime(1900, 1, 1)
seconds_time_a = a_timedelta.total_seconds()
seconds_time_b = b_timedelta.total_seconds()
#Take one from each other for minutes
time_in_minutes = (seconds_time_a - seconds_time_b) / 60
#Then decide what to do with it
if time_in_minutes < 60: # 1 hour
print('Less than an hours do something')
else:
print('More than an hour do nothing')
minutes_diff()
DARRYL, JOHNNY and MARCIN, thanks for your solutions, problem solved!!
Andy

Python call datetime current hour?

Killing two birds with one stone, I have two questions
How can I accurately call the current date? Current hour?
And how can I accurately call a specific hour? Not specific to a day.
from datetime import date, datetime
current_time = datetime.utcnow() # Call current time
start_time = datetime.time.hour(17)
end_time = datetime.time.hour(20)
You were pretty close to an answer. Here we go.
import datetime
after importing the datetime module you just need to call:
current_time = datetime.datetime.now()
In case you wanna access the data you have the year, month, day, hour, minute, second, microsecond methods:
current_time.day # Will return 17
To specify a given hour you just have to a variable you have the datetime.time class.
An idealized time, independent of any particular day, assuming that every day has exactly 246060 seconds. (There is no notion of “leap seconds” here.) Attributes: hour, minute, second, microsecond, and tzinfo.
start_time = datetime.time(17, 25, 30) # (17:25:30)
And the same as before. Accessing data can be done by calling its methods.
start_time.hour # will return 17
Here you have the documentation: :)
datetime module
Using the datetime module in Python
Examples given with Python 3
Get current time
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S") # H - hour, M- minute, S - second
print("Current Time =", current_time)
Get current hour
from datetime import datetime
now = datetime.now()
current_hour = now.strftime("%H")
print("Current hour =", current_hour)
Get current date
from datetime import date
today = date.today()
print("Today's date:", today)
Likewise, use %S for second, %M for minute, and %H for hour.
and %d for day, %m for month, and %Y for year.
Extras
Print date and time together
from datetime import datetime
# datetime object containing current date and time
now = datetime.now()
print("now =", now)
# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)
Print according to time-zone
from datetime import datetime
import pytz
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))
tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S
sources:
Date
Time
Also check out: Similar question

How do you subtract the current time from the time five minutes ago?

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)

Find time difference between 2 time stamp values in python

import datetime
def get_time_value(timestamp):
time = datetime.datetime.fromtimestamp(timestamp)
return time.strftime("%Y-%m-%d %H:%M:%S")
I have
start_time = 1518842893.04001
end_time = 1518842898.21265
get_time_value(end_time-start_time)
It gives
1969-12-31 16:00:05
and not the correct value
'startTime': '2018-02-16 20:48:13', 'endTime': '2018-02-16 20:48:18'
To get the time difference between two timestamps, first convert them to datetime objects before the subtraction. If you do this then the result will be a datetime.timedelta object. Once you have a datetime.timedelta object you can convert it to seconds or however you want to display the time difference.
For example.
time1 = datetime.datetime.fromtimestamp(start_time)
time2 = datetime.datetime.fromtimestamp(end_time)
time_difference = time2 - time1
print(time_difference)
Output:
0:00:05.172640
Or:
print(time_difference.total_seconds())
Output:
5.17264

Categories

Resources