Difference between revisions of "Python dates"

From Noah.org
Jump to navigationJump to search
(New page: Category:Engineering Category:Python Python has built-in support for doing date arithmetic. Here are some samples: <pre> import time, datetime year = '2008' month = '1' day = '24'...)
 
Line 1: Line 1:
 
[[Category:Engineering]]
 
[[Category:Engineering]]
 
[[Category:Python]]
 
[[Category:Python]]
Python has built-in support for doing date arithmetic. Here are some samples:
+
Python has built-in support for doing date arithmetic. Here are some exercises:
 
<pre>
 
<pre>
import time, datetime
+
import datetime
  
 
year = '2008'
 
year = '2008'
Line 9: Line 9:
 
day = '24'
 
day = '24'
  
 +
# This shows how to create a datetime object based on 32 days in the past.
 
last_month = datetime.datetime.now() - datetime.timedelta(days=32)
 
last_month = datetime.datetime.now() - datetime.timedelta(days=32)
 +
# This creates a datetime object from the now time.
 
now = datetime.datetime.now()
 
now = datetime.datetime.now()
 +
# Make some other datetime from strings. I do this if I parse dates from a string.
 
other_date = datetime.datetime(year=int(year), month=int(month), day=int(day))
 
other_date = datetime.datetime(year=int(year), month=int(month), day=int(day))
 +
# This does some simple date arithmetic to calculate how many days old something is.
 
if (now - other_date).days > 31:
 
if (now - other_date).days > 31:
 
     print "Older than a month."
 
     print "Older than a month."
 
</pre>
 
</pre>

Revision as of 19:28, 27 February 2008

Python has built-in support for doing date arithmetic. Here are some exercises:

import datetime

year = '2008'
month = '1'
day = '24'

# This shows how to create a datetime object based on 32 days in the past.
last_month = datetime.datetime.now() - datetime.timedelta(days=32)
# This creates a datetime object from the now time.
now = datetime.datetime.now()
# Make some other datetime from strings. I do this if I parse dates from a string.
other_date = datetime.datetime(year=int(year), month=int(month), day=int(day))
# This does some simple date arithmetic to calculate how many days old something is.
if (now - other_date).days > 31:
    print "Older than a month."