Difference between revisions of "Python dates"
From Noah.org
Jump to navigationJump to searchm |
m |
||
Line 1: | Line 1: | ||
[[Category:Engineering]] | [[Category:Engineering]] | ||
[[Category:Python]] | [[Category:Python]] | ||
− | [[Category: | + | [[Category:Time]] |
Python has built-in support for doing date arithmetic. Here are some examples: | Python has built-in support for doing date arithmetic. Here are some examples: | ||
<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])