Más contenido relacionado
La actualidad más candente (20)
Similar a Python Programming Essentials - M23 - datetime module (20)
Más de P3 InfoTech Solutions Pvt. Ltd. (20)
Python Programming Essentials - M23 - datetime module
- 3. © SkillBrew http://skillbrew.com
Types of datetime objects
Date and Time
objects
Naive
objects
Aware
objects
3
Naive objects are not
aware of time zones and
day-light savings but they
are pretty easy to
understand
An aware object has
sufficient knowledge of
time zones and day-light
savings
- 5. © SkillBrew http://skillbrew.com
Date objects
5
from datetime import date
d = date(2013, 8, 22)
print(d.year)
print(d.month)
print(d.day)
print(d.strftime("%Y %m %d"))
Output:
2013
8
22
2013 08 22
- 7. © SkillBrew http://skillbrew.com
Time objects
7
from datetime import time
t = time(2, 30, 45)
print(t.hour)
print(t.minute)
print(t.second)
print(t.strftime("%H:%M:%S"))
Output:
2
30
45
02:30:45
- 8. © SkillBrew http://skillbrew.com
DateTime objects
8
from datetime import datetime
dt = datetime(2013, 8, 21, 2, 30, 45)
print(dt.hour)
print(dt.minute)
print(dt.second)
print(dt.strftime("%m-%d-%Y %H:%M:%S"))
Output:
2
30
45
08-21-2013
02:30:45
- 10. © SkillBrew http://skillbrew.com
Manipulating dates (2)
10
from datetime import datetime, timedelta
dt = datetime(2013, 8, 21, 2, 30, 45)
# get datetime after 5 days
add_dt = dt + timedelta(days=5)
print(add_dt.strftime("%m-%d-%Y %H:%M:%S"))
Output:
08-26-2013 02:30:45
- 11. © SkillBrew http://skillbrew.com
Manipulating dates (3)
11
from datetime import datetime, timedelta
dt = datetime(2013, 8, 21, 2, 30, 45)
# get datetime after 5 days
add_dt = dt + timedelta(days=5)
# get datetime 2 days in past
sub_dt = dt - timedelta(days=2)
print(sub_dt.strftime("%m-%d-%Y %H:%M:%S"))
Output:
08-19-2013 02:30:45
- 12. © SkillBrew http://skillbrew.com
Manipulating dates (4)
12
from datetime import datetime, timedelta
dt = datetime(2013, 8, 21, 2, 30, 45)
# get datetime after 5 days
add_dt = dt + timedelta(days=5)
# get datetime 2 days in past
sub_dt = dt - timedelta(days=2)
# comparison
print add_dt > sub_dt
Output:
True
- 13. © SkillBrew http://skillbrew.com
Manipulating dates (5)
13
from datetime import datetime, timedelta
dt = datetime(2013, 8, 21, 2, 30, 45)
# get datetime after 5 days
add_dt = dt + timedelta(days=5)
# get datetime 2 days in past
sub_dt = dt - timedelta(days=2)
# comparison
add_dt > sub_dt
# subtract
print add_dt - sub_dt
Output:
7 days, 0:00:00