-1

I am converting a datetime object to string using:

from datetime import datetime
dt = datetime.now()
dt_str = str(dt)

# Now I want to get `dt`(datetime object) back from `dt_str`

How to convert dt_str to dt?

Can anyone help me with this?

1 Answers1

0

Use strptime method. Example:

from datetime import datetime

date_string = "2020-03-14"
date_object = datetime.strptime(date_string, "%Y-%m-%d")
  • %Y - Year in four digits. Example: 2018, 2019 etc.
  • %m - Month as a zero-padded decimal number. Example: 01, 02, ..., 12
  • %d - Represents the day of the month. Example: 01, 02, ..., 31
Rykov7
  • 11
  • 3