【问题标题】:Calculating end-time from user given start-time and minutes in Python在 Python 中根据用户给定的开始时间和分钟计算结束时间
【发布时间】:2022-01-07 11:39:21
【问题描述】:

我正在尝试计算并在我的数据库中存储一个结束时间(格式为 hh:mm:ss),因为我添加了“x”分钟的用户输入开始时间(格式为 hh:mm)。

Python 提供了哪些工具来帮助解决这个问题?

编辑:对不起,我匆忙发布了这个问题。请允许我添加更多细节!

我需要解析用户给出的输入时间。我使用 Flask WTForms 让用户以“hh:mm”格式输入开始时间

然后我想获取该表单数据,向其中添加“x”分钟,并将其作为 TIME 字段存储在我的数据库中,其格式为“hh:mm:ss”。

【问题讨论】:

标签: python


【解决方案1】:

 这可能是一个强烈推荐的工具 (pandas) 的简单示例,它允许您处理 datetime 的实例以及将SQL 数据插入数据库的方法

>>> 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

将存储在 DataFrame 中的记录写入 SQL 数据库: 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()

【讨论】:

    【解决方案2】:

    您可以使用datetime 模块。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 2019-09-05
      • 1970-01-01
      相关资源
      最近更新 更多