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'...) |
m |
||
(3 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
[[Category:Engineering]] | [[Category:Engineering]] | ||
[[Category:Python]] | [[Category:Python]] | ||
− | Python has built-in support for doing date arithmetic. Here are some | + | [[Category:Time]] |
+ | Python has built-in support for doing date arithmetic. Here are some examples: | ||
<pre> | <pre> | ||
− | import | + | import datetime |
year = '2008' | year = '2008' | ||
Line 9: | Line 10: | ||
day = '24' | 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) | 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.") |
+ | # 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 10:37, 13 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])