-2

I want to pass user input to a DB query as a datetime object and thought this might work but I get an error:

    start_date = "2022-07-29" #this is the user input
    start = datetime.datetime(start_date) 
    

Do I really have to split the string etc. to make it work?

MaxFrost
  • 91
  • 6
  • 1
    I don't get it. Following the second line, your `start_date` is a `datetime.datetime`. So what is `datetime.datetime(start_date)` supposed to do? – khelwood Aug 23 '22 at 12:11
  • Now that you say it that doesn´t make sense yeah... anyway the underlying problem is that I don´t know how to pass the input other than using ´split´ on the string – MaxFrost Aug 23 '22 at 12:17
  • That's a string, not an int. Shouldn't you be asking how to parse that string into a `date` or `datetime` ? Have you tried using `datetime.strptime` ? – Panagiotis Kanavos Aug 23 '22 at 12:19
  • 1
    Does this answer your question? [Convert string "Jun 1 2005 1:33PM" into datetime](https://stackoverflow.com/questions/466345/convert-string-jun-1-2005-133pm-into-datetime) – Panagiotis Kanavos Aug 23 '22 at 12:20
  • This is an XY question. You don't want to put in a string as an integer, you want to parse the date from a string. – shadowtalker Aug 23 '22 at 12:20
  • it actually asks me for an int – MaxFrost Aug 23 '22 at 12:20
  • Which means you're using the wrong method. Use `datetime.strptime` to Parse a STRing into a dateTIME – Panagiotis Kanavos Aug 23 '22 at 12:22
  • At least if you close for any reason, close for the reason that it's a duplicate of the one @PanagiotisKanavos linked. – shadowtalker Aug 23 '22 at 12:23
  • @shadowtalker there were multiple close reasons. When I added the duplicate there was already an `unclear` vote. I suspect if the third vote was also `unclear` (which it is), that got picked as the single close reason – Panagiotis Kanavos Aug 23 '22 at 14:25

1 Answers1

1
>>> import datetime
>>> start_date = "2022-07-29"                                       
>>> dt = datetime.datetime.strptime(start_date,"%Y-%m-%d") 
>>> str(dt)
'2022-07-29 00:00:00'
MortenB
  • 2,749
  • 1
  • 31
  • 35