0

I have this date as a string birthday = "2000-01-23 00:00:00"

How do I turn it into a datetime.datetime object, so when I print birthday it prints out datetime.datetime(2000, 1, 23, 0, 0)

birthday = "2000-01-23 00:00:00"
# birthday = datetime object
print(birthday)
Jackie
  • 372
  • 5
  • 16
  • look at the documentation of the `datetime` module in particular at `datetime.strptime()` ( https://docs.python.org/3.5/library/time.html#time.strptime ) if you want to parse more complicated texts then better look at `dateutils`, which is not part of the python standard modules, but can be installed with `pip install python-dateutil` – gelonida Nov 08 '19 at 01:38
  • Does this answer your question? [Parsing time string in Python](https://stackoverflow.com/questions/10494312/parsing-time-string-in-python) – Boris Verkhovskiy Nov 08 '19 at 02:03

4 Answers4

0

you can use strptimelike this

import datetime

date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
0

You can use the third party dateutil library:

You can install it with:

pip install python-dateutil


from dateutil import parser
parser.parse("2000-01-23 00:00:00")  # datetime.datetime(2000, 1, 23, 0, 0)
  • You can format code by indenting it with four spaces, or selecting it and clicking the button that looks like this: `{}`, not by making it **bold**. – Boris Verkhovskiy Nov 08 '19 at 02:01
0

this is what I would do:

datetime =datetime.strptime(birthday, "%Y-%m-%d %H:%M:%S")
0

try:

from datetime import datetime

birthday = "2000-01-23 00:00:00"

birthday_object = datetime.strptime(birthday, '%Y-%m/%d %H:%M:%S')

Also, I recommend you to take a look at the official documentation.

magraf
  • 420
  • 5
  • 8