timedelta - most elegant way to pass 'days=-5' from string
Clash Royale CLAN TAG#URR8PPP
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.
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
starting_date = datetime.today() - timedelta(delta_offset)
It doesnt like this because delta_offset is a string. I know i could modify the function to just include the offset and store -5 in my database, like what is below. But I really wanted to store days=-5 in the database because my offset can be hours as well. 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
starting_date = datetime.today() - timedelta(days=delta_offset)
timedelta
Do you realize that you're subtracting a negative offset, thus you're actually getting a later time?
– John Gordon
Aug 12 at 1:23
2 Answers
2
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.
Then you can pass these to timedelta in a dictionary and unpacking. Like so:
'days=-5'
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. Here's how:
'days=-5'
'='
offset = 'days=-5'
unit, value = offset.split('=')
starting_date = datetime.today() - timedelta(**unit: int(value))
this is super helpful.
– personalt
Aug 12 at 1:32
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)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You should probably store the number of seconds in the database (or whatever the smallest unit your offset can be), and then use that to build the
timedelta
.– Patrick Haugh
Aug 12 at 1:23