Difference between revisions of "Python dates"
From Noah.org
Jump to navigationJump to searchm |
|||
Line 1: | Line 1: | ||
[[Category:Engineering]] | [[Category:Engineering]] | ||
[[Category:Python]] | [[Category:Python]] | ||
− | Python has built-in support for doing date arithmetic. Here are some | + | Python has built-in support for doing date arithmetic. Here are some examples: |
<pre> | <pre> | ||
import datetime | import datetime | ||
Line 9: | Line 9: | ||
day = '24' | day = '24' | ||
− | # This shows how to create a datetime object based | + | # This shows how to create a datetime object based 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. | # This creates a datetime object from the now time. | ||
Line 17: | Line 17: | ||
# This does some simple date arithmetic to calculate how many days old something is. | # 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.") |
+ | # Datetimestamp strings (DTS) are always handy for naming things. | ||
+ | # This creates a string encoding of the current date and time at UTC 0. | ||
+ | # Use localtime() instead of gmtime() if you want time in your current timezone. | ||
+ | dts_string = ("%04d%02d%02d%02d%02d%02d" % time.gmtime()[0:6]) | ||
</pre> | </pre> |
Revision as of 16:56, 10 November 2014
Python has built-in support for doing date arithmetic. Here are some examples:
import datetime year = '2008' month = '1' day = '24' # This shows how to create a datetime object based 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.") # Datetimestamp strings (DTS) are always handy for naming things. # This creates a string encoding of the current date and time at UTC 0. # Use localtime() instead of gmtime() if you want time in your current timezone. dts_string = ("%04d%02d%02d%02d%02d%02d" % time.gmtime()[0:6])