Python Forum

Full Version: how to convert and format a varable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi
can any one pls help me with convering and formating the variable timeset so my cod can work.
it works only if i replace the timeset variable with the date.

import datetime
 
# to get today's date
today = datetime.date.today()
timeset = "2020, 5, 29" 
# code works when i put the date of timeset variable here
thedate = datetime.date(timeset)
 
# to get delta in days form today (this is an absolute value)
delta = today - thedate
 
print(f"The delta is {delta.days} days")


if delta.days > 0:
     print("dags")

elif delta.days < 365:
     print("inte dags")
Couple things. Don't use commas in your timeset, and use a different function for the conversion. The following works:
import datetime
from datetime import datetime as dt
  
# to get today's date
today = datetime.date.today()
timeset = "2020 05 29" 
# code works when i put the date of timeset variable here
thedate = dt.strptime(timeset, '%Y %m %d').date()
  
# to get delta in days form today (this is an absolute value)
delta = today - thedate
  
print(f"The delta is {delta.days} days")
 
 
if delta.days > 0:
     print("dags")
 
elif delta.days < 365:
     print("inte dags")
import datetime

today = datetime.date.today()

thedate = datetime.date(2020, 5, 29)

delta = today - thedate
  
print(f"The delta is {delta.days} days")
Output:
The delta is 730 days
(May-29-2022, 12:15 PM)Larz60+ Wrote: [ -> ]
import datetime

today = datetime.date.today()

thedate = datetime.date(2020, 5, 29)

delta = today - thedate
  
print(f"The delta is {delta.days} days")
Output:
The delta is 730 days

Yes i know this was the only way i could make it work and this was how the code looked originally . I wrote it but mayby i did not make it clear. my bad. I need to use a variable with the date in this code its how this bit of code is going in to the bigger code.
(May-29-2022, 11:57 AM)jefsummers Wrote: [ -> ]Couple things. Don't use commas in your timeset, and use a different function for the conversion. The following works:
import datetime
from datetime import datetime as dt
  
# to get today's date
today = datetime.date.today()
timeset = "2020 05 29" 
# code works when i put the date of timeset variable here
thedate = dt.strptime(timeset, '%Y %m %d').date()
  
# to get delta in days form today (this is an absolute value)
delta = today - thedate
  
print(f"The delta is {delta.days} days")
 
 
if delta.days > 0:
     print("dags")
 
elif delta.days < 365:
     print("inte dags")

Thanks a lot. works like a charm Big Grin