0

I am trying to look at other stackoverflow posts like this about converting date & time strings to datetime objects but not having any luck for specifically what I am after.

from datetime import datetime

s = '2020-07-12T19:30'
f = "%Y-%m-%dT%H:%M"
out = datetime.strptime(s, f)

print(out)

This works outputs 2020-07-12 19:30:00

But how do I convert s for a format like print(datetime.now())?

Which prints like: datetime.datetime(2021, 7, 9, 12, 36, 24, 108816)

wjandrea
  • 28,235
  • 9
  • 60
  • 81
bbartling
  • 3,288
  • 9
  • 43
  • 88
  • 2
    What version of Python are you using? For `print(datetime.now())`, I get `2021-07-09 13:50:55.586161` on Python 3.8.0. – wjandrea Jul 09 '21 at 17:51
  • I am using anaconda Jupyter labs – bbartling Jul 09 '21 at 17:58
  • But what version of *Python* are you using? – wjandrea Jul 09 '21 at 17:59
  • 1
    version 3.8 anaconda jupyter labs – bbartling Jul 09 '21 at 17:59
  • It's just because you haven't captured seconds & microseconds I believe. I was able to generate your desired outcome. (It wont show up if the value is zero) Try giving this: `s = '2020-07-12T19:30:1:2'` `f = "%Y-%m-%dT%H:%M:%S:%f"` – Akash Unni Jul 09 '21 at 18:01
  • That throws an error, `ValueError: time data '2020-07-12T19:30' does not match format '%Y-%m-%dT%H:%M:%S:%f'` Any ideas to try? Thanks so much... – bbartling Jul 09 '21 at 18:14
  • I did not get the error because I've specified seconds & microseconds in the variable `s`. If you don't have seconds value in your data, then there's no way since, it shows up only non-zero values while printing. Try taking the varibles I took in my example – Akash Unni Jul 09 '21 at 18:25
  • Oh got it I see I have add in seconds and microseconds to my data some how. The data comes from html form inputs to a date and time picker. That doesn't appear to automatically provide seconds and microseconds to my very limited knowledge – bbartling Jul 09 '21 at 18:34

0 Answers0