Last active
April 21, 2016 00:37
-
-
Save yoki/c6ddacd8f87ce7cdfb1bb506ae621d11 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#--------------------------------- | |
# Converting Strings into Datetimes | |
#--------------------------------- | |
from datetime import datetime | |
text = '2012-09-20' | |
y = datetime.strptime(text, '%Y-%m-%d') | |
# for more, check http://strftime.org/ | |
#--------------------------------- | |
# Converting Datetimes into String | |
#--------------------------------- | |
import datetime | |
from datetime.datetime import strftime as ft | |
z = datetime.datetime(2012, 9, 8, 7, 4, 3, 177393) | |
ft(z, '%Y-%m-%D %H:%M:%S') #=> '2012-09-08 07:04:03' | |
'{d.year}/{d.month}/{d.day} {d.hour}:{d.minute}:{d.second}'.format(d=z) | |
# => '2012-9-8 7:4:3' | |
datetime.isotime() #=> '2012-09-23T07:04:03' | |
ft(z, '%c') #=> 'Mon Sep 8 07:06:05 2012' | |
ft(z, '%x') #=> '2012-09-08' | |
ft(z, '%X') #=> '07:04:03' | |
# for more, check http://strftime.org/ | |
#--------------------------------- | |
# DateTime Algebra | |
#--------------------------------- | |
# http://chimera.labs.oreilly.com/books/1230000000393/ch03.html#_solution_52 | |
from datetime import timedelta | |
a = timedelta(days=2, hours=6) | |
b = timedelta(hours=4.5) | |
c = a + b | |
c.days #=> 2 | |
c.seconds #=> 37800 | |
c.seconds / 3600 #=> 10.5 | |
c.total_seconds() / 3600 #=> 58.5 | |
# If you need to represent specific dates and times, | |
# create datetime instances and use the standard mathematical operations to manipulate them. | |
from datetime import datetime | |
a = datetime(2012, 9, 23) | |
print(a + timedelta(days=10)) #=> 2012-10-03 00:00:00 | |
b = datetime(2012, 12, 21) | |
d = b - a | |
d.days #=> 89 | |
now = datetime.today() | |
print(now + timedelta(minutes=10)) #=> 2012-12-21 15:04:43.094063 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment