Datetime conversion(Datetime to String, String to datetime and days subtraction from datetime) in Python
Published on: 15th September 2018
This tutorial explains how to do datetime (Datetime to String, String to datetime and days subtraction from datetime) conversion in Python
Abstract
In this tutorial we will convert Datetime to String, String to datetime and days subtraction from datetime.
Implementation
In below mention code we will use strftime, strptime and timedelta for datetime conversion.
Converting Datetime into String
from datetime import datetime, timedelta
#datetime to string conversion
t = datetime(2018, 2, 23, 0, 0)
value = t.strftime('%m/%d/%Y')
print value
Output:
02/23/2018
Converting String into Datetime
from datetime import datetime, timedelta
#string to Datetime conversion
val = '02/23/2018'
date_time = datetime.strptime(val, '%m/%d/%Y')
print date_time
Output:
2018-02-23 00:00:00
Subtracting days from Datetime
from datetime import datetime, timedelta
#days subtraction from datetime
days_to_subtract = 7
dt = datetime(2018, 2, 23, 0, 0)
date_subtract = dt - timedelta(days=days_to_subtract)
print date_subtract
Output:
2018-02-16 00:00:00
Thank you for reading through the tutorial. In case of any feedback/questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.
Published on: 15th September 2018
Comment Form is loading comments...