简体   繁体   English

timedelta-从字符串传递'days = -5'的最优雅方法

[英]timedelta - most elegant way to pass 'days=-5' from string

I am trying call a function that triggers a report to be generated with a starting date that is either hour or days ago. 我正在尝试调用一个函数,该函数会触发以小时或几天前的开始日期生成报告。 The code below works fine but I would like to store the timedelta offset in a mysql database. 下面的代码工作正常,但我想将timedelta偏移量存储在mysql数据库中。

starting_date = datetime.today() - timedelta(days=-5)

I had hoped to store 'days=-5' in the database, extract that database column to variable 'delta_offset' and then run 我曾希望将“ days = -5”存储在数据库中,将该数据库列提取到变量“ delta_offset”,然后运行

starting_date = datetime.today() - timedelta(delta_offset)

It doesnt like this because delta_offset is a string. 它不喜欢这样,因为delta_offset是一个字符串。 I know i could modify the function to just include the offset and store -5 in my database, like what is below. 我知道我可以修改函数以仅在数据库中包含offset并存储-5,如下所示。 But I really wanted to store days=-5 in the database because my offset can be hours as well. 但是我真的想在数据库中存储days = -5,因为我的偏移量也可以是几小时。 I could make my offset in database always hours and store -120 in the database but was wondering if there was an elegant way where I store 'days=-5' in the database and not cause type issues 我可以使数据库中的偏移量始终为小时,并在数据库中存储-120,但是我想知道是否存在一种优雅的方式在数据库中存储“ days = -5”而不会导致类型问题

starting_date = datetime.today() - timedelta(days=delta_offset)

Instead of storing 'days=-5' in your database as a single column, you could break this into two columns named 'value' and 'unit' or similar. 与其将'days=-5'存储在数据库中而不是作为单列,您可以将其分为名为“值”和“单位”或类似名称的两列。 Then you can pass these to timedelta in a dictionary and unpacking. 然后,您可以将它们通过字典传递给timedelta并解压缩。 Like so: 像这样:

unit = 'days'
value = -5
starting_date = datetime.today() - timedelta(**{unit: value})

This will unpack the dictionary so you get the same result as doing timedelta([unit]=value) . 这将解压缩字典,因此您得到的结果与timedelta([unit]=value)

Alternatively, if you really would like to keep 'days=-5' as a value of a single column in your database, you could split the string on '=' then take a similar approach. 另外,如果您确实希望将'days=-5'保留为数据库中单个列的值,则可以在'='上拆分字符串,然后采取类似的方法。 Here's how: 这是如何做:

offset = 'days=-5'
unit, value = offset.split('=')
starting_date = datetime.today() - timedelta(**{unit: int(value)})

i would do it this way: 我会这样做:

    date_offset_split = date_offset.split("=")
    kwargs = {date_offset_split[0]: int(date_offset_split[1])}

    starting_date = datetime.today() - timedelta(**kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM