Reputation: 719
I am trying to calculate and store an end-time (formatted as hh:mm:ss) in my database given a user input start-time (formatted as hh:mm) that I add 'x' minutes to.
What tools does Python offer to help with this?
EDIT: Sorry I hastily posted this question. Allow me to add more specifics!
I need to parse an input time given by the user. I use Flask WTForms to have the user input a start time in the format "hh:mm"
I then want to take that form data, add 'x' minutes to it, and store it in my database as a TIME field, which is formatted as "hh:mm:ss".
Upvotes: 0
Views: 854
Reputation: 1602
This could be a simple example of a highly recommended tool (pandas), it allows you to handle instances of datetime
and methods to insert SQL
data into your database.
>>> user_starts # user starts input
array([[36506], [33486], [25414], [33987],
[37577], [ 4320], [40926], [24995],
[13390], [36733], [19153], [29232],
[30907], [13180], [21200], [23616],
[ 4033], [ 9284], [31117], [18431]])
>>> df = pd.DataFrame(user_starts, colums=['id'])
>>> df['Time'] = pd.date_range(start='11/30/2021', periods=len(user_starts), freq='H')
>>> df.head()
id Time
0 36506 2021-11-30 00:00:00
1 33486 2021-11-30 01:00:00
2 25414 2021-11-30 02:00:00
3 33987 2021-11-30 03:00:00
4 37577 2021-11-30 04:00:00
Write records stored in a DataFrame to a SQL database:
sqlalchemy
>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite://', echo=False)
>>> df.to_sql(['id', 'Time'], con=engine)
>>> engine.execute("SELECT * FROM users").fetchall()
Upvotes: 1
Reputation: 89264
You can use the datetime
module.
import datetime
start_time = datetime.datetime.strptime('11:23', '%H:%M') # parse time
end_time = start_time + datetime.timedelta(minutes = 5) # add minutes
print(datetime.datetime.strftime(end_time, '%H:%M:%S')) # format and print
# 11:28:00
Upvotes: 2