Learning Python Date Formatting is another important step involved in mastering the popular programming language. Learn more here.
Python Date Formatting
Time between two date-times
from datetime import datetime
a = datetime(2016,10,06,0,0,0)
b = datetime(2016,10,01,23,59,59)
a-b
datetime.timedelta(4, 1)
(a-b).days
4
(a-b).total_seconds()
518399.0
Creating Date Objects
To create a date, we can use the datetime()
class (constructor) of the datetime
module.
The datetime()
class requires three parameters to create a date: year, month, day.
Example
Create a date object:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
The datetime()
class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and has a default value of 0
, (None
for timezone).
Python Date Formatting: Outputting datetime object to string
Uses C standard format codes.
from datetime import datetime
datetime_for_string = datetime(2016,10,1,0,0)
datetime_string_format = '%b %d %Y, %H:%M:%S'
datetime.strftime(datetime_for_string,datetime_string_format)
Oct 01 2016, 00:00:00
Python Date Formatting: Parsing string to datetime object
Uses C standard format codes.
from datetime import datetime
datetime_string = 'Oct 1 2016, 00:00:00'
datetime_string_format = '%b %d %Y, %H:%M:%S'
datetime.strptime(datetime_string, datetime_string_format)
datetime.datetime(2016, 10, 1, 0, 0)
Must Read Python Interview Questions
200+ Python Tutorials With Coding Examples
Other Python Tutorials
- What is Python?
- Python Advantages
- Python For Beginners
- Python For Machine Learning
- Machine Learning For Beginners
- 130+ Python Projects With Source Code On GitHub