Difference between revisions of "Python dates"
From Noah.org
Jump to navigationJump to searchm |
m |
||
Line 2: | Line 2: | ||
[[Category:Python]] | [[Category:Python]] | ||
[[Category:Time]] | [[Category:Time]] | ||
+ | |||
+ | |||
+ | == Timestamps == | ||
+ | |||
+ | <pre> | ||
+ | # This gives the same results as time.time(). | ||
+ | (datetime.datetime.utcnow() - datetime.datetime(1970,1,1)).total_seconds() | ||
+ | time.time() | ||
+ | </pre> | ||
+ | |||
+ | <pre> | ||
+ | import datetime | ||
+ | datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f UTC") | ||
+ | </pre> | ||
+ | |||
+ | |||
+ | == Date arithmetic == | ||
+ | |||
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> |
Latest revision as of 14:25, 5 April 2019
Timestamps
# This gives the same results as time.time(). (datetime.datetime.utcnow() - datetime.datetime(1970,1,1)).total_seconds() time.time()
import datetime datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f UTC")
Date arithmetic
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])