0

Python: Converting string to datetime object

To convert a datetime derived from a string/text in python, we will be using strptime() method, this was came from built in function of datetime class.

Question: Why do we need converting it to datetime object?
Answer:  For us to manipulate it, like adding/subtracting days, parsing/processing/transforming it with different date formats and any other uses.


Syntax:

datetime.strptime(givenDate,dateFormat)

Parameters:

givenDate – should be a string/text. Example: “2022-03-01 12:12:00”
dateFormat – should be the date format matching the givenDate otherwise it will throw an exception. Example: ‘%Y-%m-%d %H:%M:%S’

 

Example:

from datetime import datetime

givenDate = "2022-03-01 12:12:00"

date_obj = datetime.strptime(givenDate, '%Y-%m-%d %H:%M:%S')

print(date_obj)

Above snippet code will print the following:

C:\python>python string_date.py
2022-03-01 12:12:00

 

Example 1: Adding 1 day to the date object:
In this example, we will be using timedelta(), its pretty straightforward how to use it, see below:

from datetime import datetime, timedelta

givenDate = "2022-03-01 12:12:00"

date_obj = datetime.strptime(givenDate, '%Y-%m-%d %H:%M:%S')

date_obj = date_obj + timedelta(days=1)

print(date_obj)

Above snippet code will print the following:

C:\python>python string_date_2.py
2022-03-02 12:12:00

 

 

Kevin San Jose, VCP6-DCV

Kevin San Jose, VCP6-DCV

LFCS, MTCRE, VCP6-DCV

Leave a Reply

Your email address will not be published. Required fields are marked *