-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
  • Take a look at the datetime.strftime function in python. Commented Mar 14, 2022 at 9:34

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.