<< Back to PYTHON
Python Datetime Methods: Date, Timedelta
Use the datetime module. Parses date strings and perform other useful tasks.Datetime. In amber an insect is preserved for millions of years. A volcano erupts. A meteor hits earth. Existence in amber is unchanging.
In the current time (and of no concern to the insect) we use Python's datetime module to handle dates. This module parses strings containing dates.
Parse. To parse we have the strptime method in datetime. The name is confusing—it comes from the C standard library. This method requires two arguments.
Arguments: The first argument is a string containing date information. The second argument is the format string.
Format codes
B: The full month name.
d: The digit of the day of the month.
Y: The four-digit year.
Python program that uses strptime
from datetime import datetime
# Input string.
s = "August 16, 2012"
# Use strptime.
d = datetime.strptime(s, "%B %d, %Y")
print(d)
Output
2012-08-16 00:00:00
Exact date. Suppose you know the exact date you want to represent in a Python datetime. We can use a special constructor to get this date—no parsing is required.
Python program that uses datetime for exact date
from datetime import datetime
# This is 20017, march 3, at 5:30 in the morning.
# ... Hope you like getting up early.
result = datetime(2017, 3, 1, 5, 30)
print("DATETIME", result)
# Verify the month.
print("MONTH", result.month)
Output
DATETIME 2017-03-01 05:30:00
MONTH 3
Yesterday. This is always the current date minus one day. In Python we compute this with timedelta. This type resides in the datetime module.
Here: We introduce a method called yesterday(). It calls today() and then subtracts a timedelta of 1 day.
Tip: A timedelta can be subtracted or added to a date object. In this way, we compute yesterday, today and any other relative day.
Python program that returns yesterday
from datetime import date
from datetime import timedelta
def yesterday():
# Get today.
today = date.today()
# Subtract timedelta of 1 day.
yesterday = today - timedelta(days=1)
return yesterday
print(date.today())
print(yesterday())
Output
2013-02-21
2013-02-20
Tomorrow. This is the best day to do an annoying task. It is computed in the same way as yesterday. We add a timedelta of one day to the current day. Here we use a shorter method body.
Info: Helper methods, such as tomorrow and yesterday, are a useful abstraction in certain programs. They are reusable.
Python program that gets tomorrow
from datetime import date
from datetime import timedelta
def tomorrow():
# Add one day delta.
return date.today() + timedelta(days=1)
print(date.today())
print(tomorrow())
Output
2013-02-21
2013-02-22
Sort dates. A list of dates can be sorted. Suppose a program has an unordered list of dates. Often we will need to order them chronologically, from first to last (or in reverse).
ListHere: We create a list and append four new dates to it. These are all dates in the future. They are not chronologically ordered.
Then: We invoke the sort method on the list. In a for-loop, we display the dates, now ordered from first to last in time.
Python program that sorts date list
from datetime import date, timedelta
# Create a list of dates.
values = []
values.append(date.today() + timedelta(days=300))
values.append(date.today() + timedelta(days=2))
values.append(date.today() + timedelta(days=1))
values.append(date.today() + timedelta(days=20))
# Sort the list.
values.sort()
# Display.
for d in values:
print(d)
Output
2013-10-13
2013-10-14
2013-11-01
2014-08-08
Timedelta. No two points in time are the same. In Python we express the difference between two dates with timedelta. To use timedelta, provide the arguments using names.
Here: In this program, we subtract one hour from one day. And, as you might expect, the result is 23 hours.
Python program that uses timedelta
from datetime import timedelta
# This represents 1 day.
a = timedelta(days=1)
# Represents 1 hour.
b = timedelta(hours=1)
# Subtract 1 hour from 1 day.
c = a - b
print(c)
Output
23:00:00
Timedelta arguments. Next, we consider the possible arguments to timedelta in more detail. You can specify more than argument to timedelta—simply use a comma to separate them.
Note: Large units like years, and small units, like nanoseconds, are not included in the Timedelta calls.
Timedelta arguments, smallest to largest
microseconds,
milliseconds,
seconds,
minutes,
hours,
days,
weeks
File, timestamps. This program uses the os.path and date modules. It gets the access, modification and creation of time of a file. You will need to change the file name to one that exists.
os.pathFloat: In many programs we prefer a date type, not a float type. Dates are easier to understand and print.
So: We use the fromtimestamp method from the date module. This converts, correctly, the floats to dates.
Tip: I verified that the three dates are correct in this program according to Windows 8.1.
Python program that gets timestamps, converts to dates
from os import path
from datetime import date
# Get access, modification and creation time.
a = path.getatime("/enable1.txt")
m = path.getmtime("/enable1.txt")
c = path.getctime("/enable1.txt")
# Display the times.
print(a, m, c)
# Convert timestamps to dates.
a2 = date.fromtimestamp(a)
m2 = date.fromtimestamp(m)
c2 = date.fromtimestamp(c)
print(a2, m2, c2)
Output, format edited
1360539846.3326 1326137807.9652 1360539846.3326
2013-02-10 2012-01-09 2013-02-10
Range. It is easy to get a range of dates. Suppose we have a start date and want the next 10 days. Loop over 1 through 10, and use timedelta to add that number of days to the original date.
Here: We get today. We then add one to ten days to today. This yields the next 10 days.
RangePython program that gets future dates, range
from datetime import date, timedelta
# Start with today.
start = date.today()
print(start)
# Add 1 to 10 days and get future days.
for add in range(1, 10):
future = start + timedelta(days=add)
print(future)
Output
2014-04-21
2014-04-22
2014-04-23
2014-04-24
2014-04-25
2014-04-26
2014-04-27
2014-04-28
2014-04-29
2014-04-30
Time. With this method we get a number that indicates the total number of seconds in the time. An epoch is a period of time. For UNIX time the epoch begins at year 1970.
So: The seconds returned by this program equal 46 years—the example is being tested in 2016.
Quote: Return the time in seconds since the epoch as a floating point number.
Time: Python.orgPython program that uses time method
import time
# Get current seconds.
current = time.time()
print("Current seconds:", current)
Output
Current seconds: 1471905804.3763597
Struct_time. To get detailed times, we use a method like gmtime() and then access parts of the returned struct_time. Here we access the year, month, hour and other properties.
Days: Month days is the index of the day in the current month. So the 22nd of a month has "mday" of 22—this begins at index 1 not 0.
Also: Weekdays and year days are indexes within those larger time ranges. Monday is "wday" 0.
Python program that uses struct_time
import time
# Get a struct indicating the current time.
current = time.gmtime()
# Get year.
print("Year:", current.tm_year)
# Get month.
print("Month:", current.tm_mon)
# Get day of month.
print("Month day:", current.tm_mday)
# Get hour.
print("Hour:", current.tm_hour)
# Get minute.
print("Minute:", current.tm_min)
# Get seconds.
print("Second:", current.tm_sec)
# Get day of week.
print("Week day:", current.tm_wday)
# Get day of year.
print("Year day:", current.tm_yday)
# Get whether daylight saving time.
print("Is DST:", current.tm_isdst)
Output
Year: 2016
Month: 8
Month day: 22
Hour: 22
Minute: 48
Second: 8
Week day: 0
Year day: 235
Is DST: 0
Benchmark, cache. Getting the date, as with date.today(), is slow. This call must access the operating system. An easy way to optimize this is to cache dates.
Version 1: This loop access date.today() once on each iteration through the loop. It runs much slower.
Version 2: The date.today() call is cached in a variable before the loop runs. This makes each iteration much faster. We hoist the call.
Result: This optimization clearly improves the performance of accessing a date. But it comes with serious limitations.
Python program that benchmarks cached date
import time
from datetime import date
# Time 1.
print(time.time())
# Version 1: accesses today in a loop.
i = 0
while i < 100000:
t = date.today()
if t.year != 2013:
raise Exception()
i += 1
# Time 2.
print(time.time())
# Version 2: accesses today once.
i = 0
t = date.today()
while i < 100000:
if t.year != 2013:
raise Exception()
i += 1
# Time 3.
print(time.time())
Output
1361485333.238
1361485333.411 Loop 1 = 0.173
1361485333.435 Loop 2 = 0.024
Filename, date.today. We can generate files with the current date in the filename. This is an effective approach for logging programs (or any program that is run once per day).
Filename, Date
Some research. Human beings like to make things as complicated as possible. This is true with dates and times. We apply political concepts like daylight saving time.
Quote: An aware object has sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information.... A naive object does not....
Datetime: Python.org
A review. The Python environment has strong support for time handling. These libraries are built into the environment. They do not need to be recreated in each program.
This yields faster, more reliable software. Certain aspects of time handling, such as computing calendar dates by offsets, is best left to sophisticated libraries.
Related Links:
- Python global and nonlocal
- Python not: If Not True
- Python Convert Decimal Binary Octal and Hexadecimal
- Python Tkinter Scale
- Python Tkinter Scrollbar
- Python Tkinter Text
- Python History
- Python Number: random, float and divmod
- Python Tkinter Toplevel
- Python Tkinter Spinbox
- Python Tkinter PanedWindow
- Python Tkinter LabelFrame
- Python Tkinter MessageBox
- Python Website Blocker
- Python Console Programs: Input and Print
- Python Display Calendar
- Python Check Number Odd or Even
- Python readline Example: Read Next Line
- Python Anagram Find Method
- Python Any: Any Versus All, List Performance
- Python Filename With Date Example (date.today)
- Python Find String: index and count
- Python filter (Lambda Removes From List or Range)
- Python ASCII Value of Character
- Python Sum Example
- Python make simple Calculator
- Python Add Two Matrices
- Python Multiply Two Matrices
- Python SyntaxError (invalid syntax)
- Python Transpose Matrix
- Python Remove Punctuation from String
- Python Dictionary items() method with Examples
- Python Dictionary keys() method with Examples
- Python Textwrap Wrap Example
- Python Dictionary popitem() method with Examples
- Python Dictionary pop() method with Examples
- Python HTML: HTMLParser, Read Markup
- Python Tkinter Tutorial
- Python Array Examples
- Python ord, chr Built Ins
- Python Dictionary setdefault() method with Examples
- Python Dictionary update() method with Examples
- Python Dictionary values() method with Examples
- Python complex() function with Examples
- Python delattr() function with Examples
- Python dir() function with Examples
- Python divmod() function with Examples
- Python Loops
- Python for loop
- Python while loop
- Python enumerate() function with Examples
- Python break
- Python continue
- Python dict() function with Examples
- Python pass
- Python Strings
- Python Lists
- Python Tuples
- Python Sets
- Python Built-in Functions
- Python filter() function with Examples
- Python dict Keyword (Copy Dictionary)
- Python Dictionary Order Benchmark
- Python Dictionary String Key Performance
- Python 2D Array: Create 2D Array of Integers
- Python Divmod Examples, Modulo Operator
- bin() in Python | Python bin() Function with Examples
- Python Oops Concept
- Python Object Classes
- Python Constructors
- Python hash() function with Examples
- Python Pandas | Python Pandas Tutorial
- Python Class Examples: Init and Self
- Python help() function with Examples
- Python IndentationError (unexpected indent)
- Python Index and Count (Search List)
- Python min() function with Examples
- Python classmethod and staticmethod Use
- Python set() function with Examples
- Python hex() function with Examples
- Python id() function with Examples
- Python sorted() function with Examples
- Python next() function with Examples
- Python Compound Interest
- Python List insert() method with Examples
- Python Datetime Methods: Date, Timedelta
- Python setattr() function with Examples
- Python 2D List Examples
- Python Pandas Data operations
- Python Def Methods and Arguments (callable)
- Python slice() function with Examples
- Python Remove HTML Tags
- Python input() function with Examples
- Python enumerate (For Index, Element)
- Python Display the multiplication Table
- Python int() function with Examples
- Python Error: Try, Except and Raise
- Python isinstance() function with Examples
- Python oct() function with Examples
- Python startswith, endswith Examples
- Python List append() method with Examples
- Python NumPy Examples (array, random, arange)
- Python Replace Example
- Python List clear() method with Examples
- Python List copy() method with Examples
- Python Lower Dictionary: String Performance
- Python Lower and Upper: Capitalize String
- Python Dictionary Examples
- Python map Examples
- Python Len (String Length)
- Python Padding Examples: ljust, rjust
- Python Type: setattr and getattr Examples
- Python String List Examples
- Python String
- Python Remove Duplicates From List
- Python If Examples: Elif, Else
- Python Programs | Python Programming Examples
- Python List count() method with Examples
- Python List extend() method with Examples
- Python List index() method with Examples
- Python List pop() method with Examples
- Python Palindrome Method: Detect Words, Sentences
- Python Path: os.path Examples
- Python List remove() method with Examples
- Python List reverse() method with Examples
- Top 50+ Python Interview Questions (2021)
- Python List sort() method with Examples
- Python sort word in Alphabetic Order
- abs() in Python | Python abs() Function with Examples
- Python String | encode() method with Examples
- all() in Python | Python all() Function with Examples
- any() in Python | Python any() Function with Examples
- Python Built In Functions
- ascii() in Python | Python ascii() Function with Examples
- Python bytes, bytearray Examples (memoryview)
- bool() in Python | Python bool() Function with Examples
- bytearray() in Python | Python bytearray() Function with Examples
- Python Caesar Cipher
- bytes() in Python | Python bytes() Function with Examples
- Python Sum of Natural Numbers
- callable() in Python | Python callable() Function with Examples
- Python Set add() method with Examples
- Python Set discard() method with Examples
- Python Set pop() method with Examples
- Python math.floor, import math Examples
- Python Return Keyword (Return Multiple Values)
- Python while Loop Examples
- Python Math Examples
- Python Reverse String
- Python max, min Examples
- Python pass Statement
- Python Set remove() method with Examples
- Python Dictionary
- Python Functions
- Python String | capitalize() method with Examples
- Python String | casefold() method with Examples
- Python re.sub, subn Methods
- Python subprocess Examples: subprocess.run
- Python Tkinter Checkbutton
- Python Tkinter Entry
- Python String | center() method with Examples
- Python Substring Examples
- Python pow Example, Power Operator
- Python Lambda
- Python Files I/O
- Python Modules
- Python String | count() method with Examples
- Python String | endswith() method with Examples
- Python String | expandtabs() method with Examples
- Python Prime Number Method
- Python String | find() method with Examples
- Python String | format() method with Examples
- Python String | index() method with Examples
- Python String | isalnum() method with Examples
- Python String | isalpha() method with Examples
- Python String | isdecimal() method with Examples
- Python Pandas Sorting
- Python String | isdigit() method with Examples
- Python Convert Types
- Python String | isidentifier() method with Examples
- Python Pandas Add column to DataFrame columns
- Python String | islower() method with Examples
- Python Pandas Reading Files
- Python Right String Part
- Python IOError Fix, os.path.exists
- Python Punctuation and Whitespace (string.punctuation)
- Python isalnum: String Is Alphanumeric
- Python Pandas Series
- Python Pandas DataFrame
- Python Recursion Example
- Python ROT13 Method
- Python StringIO Examples and Benchmark
- Python Import Syntax Examples: Modules, NameError
- Python in Keyword
- Python iter Example: next
- Python Round Up and Down (Math Round)
- Python List Comprehension
- Python Collection Module
- Python Math Module
- Python OS Module
- Python Random Module
- Python Statistics Module
- Python String Equals: casefold
- Python Sys Module
- Top 10 Python IDEs | Python IDEs
- Python Arrays
- Python Magic Method
- Python Stack and Queue
- Python MySQL Environment Setup
- Python MySQL Database Connection
- Python MySQL Creating New Database
- Python MySQL Creating Tables
- Python Word Count Method (re.findall)
- Python String Literal: F, R Strings
- Python MySQL Update Operation
- Python MySQL Join Operation
- Python Armstrong Number
- Learn Python Tutorial
- Python Factorial Number using Recursion
- Python Features
- Python Comments
- Python if else
- Python Translate and Maketrans Examples
- Python Website Blocker | Building Python Script
- Python Itertools Module: Cycle and Repeat
- Python Operators
- Python Int Example
- Python join Example: Combine Strings From List
- Python Read CSV File
- Python Write CSV File
- Python Read Excel File
- Python Write Excel File
- Python json: Import JSON, load and dumps
- Python Lambda Expressions
- Python Print the Fibonacci sequence
- Python format Example (Format Literal)
- Python Namedtuple Example
- Python SciPy Tutorial
- Python Applications
- Python KeyError Fix: Use Dictionary get
- Python Resize List: Slice and Append
- Python String | translate() method with Examples
- Python Copy List (Slice Entire List)
- Python None: TypeError, NoneType Has No Length
- Python MySQL Performing Transactions
- Python String | isnumeric() method with Examples
- Python MongoDB Example
- Python String | isprintable() method with Examples
- Python Tkinter Canvas
- Python String | isspace() method with Examples
- Python Tkinter Frame
- Python Tkinter Label
- Python Tkinter Listbox
- Python String | istitle() method with Examples
- Python Website Blocker | Script Deployment on Linux
- Python Website Blocker | Script Deployment on Windows
- Python String | isupper() method with Examples
- Python String split() method with Examples
- Python Slice Examples: Start, Stop and Step
- Python String | join() method with Examples
- Python String | ljust() method with Examples
- Python Sort by File Size
- Python Arithmetic Operations
- Python String | lower() method with Examples
- Python Exception Handling | Python try except
- Python Date
- Python Regex | Regular Expression
- Python Sending Email using SMTP
- Python Command Line Arguments
- Python List Comprehension Examples
- Python Assert Keyword
- Python Set Examples
- Python Fibonacci Sequence
- Python Maze Pathfinding Example
- Python Memoize: Dictionary, functools.lru_cache
- Python Timeit, Repeat Examples
- Python Strip Examples
- Python asyncio Example: yield from asyncio.sleep
- Python String Between, Before and After Methods
- Python bool Use (Returns True or False)
- Python Counter Example
- Python frozenset: Immutable Sets
- Python Generator Examples: Yield, Expressions
- Python CSV: csv.reader and Sniffer
- Python globals, locals, vars and dir
- Python abs: Absolute Value
- Python gzip: Compression Examples
- Python Function Display Calendar
- Python Display Fibonacci Sequence Recursion
- Python String | lstrip() method with Examples
- Python del Operator (Remove at Index or Key)
- Python String | partition() method with Examples
- Python String | replace() method with Examples
- Python Zip Examples: Zip Objects
- Python String | rfind() method with Examples
- Python String | rindex() method with Examples
- Python String rjust() method with Examples
- Python String rpartition() method with Examples
- Python String rsplit() method with Examples
- Python Area Of Triangle
- Python Quadratic Equation
- Python swap two Variables
- Python Generate Random Number
- Python Convert Kilometers to Miles
- Python Convert Celsius to Fahrenheit
- Python Check Number Positive Negative or Zero
- Python Check Leap Year
- Python Check Prime Number
- Top 40 Python Pandas Interview Questions (2021)
- Python Check Armstrong Number
- Python SQLite Example
- Python Tkinter Button
- Python Find LCM
- Python Find HCF
- Python Tuple Examples
- Python String | rstrip() method with Examples
- Python String splitlines() method with Examples
- Python String | startswith() method with Examples
- Python String | swapcase() method with Examples
- Python Truncate String
- Python String | upper() method with Examples
- Python for: Loop Over String Characters
- Python String | zfill() method with Examples
- Python Sort Examples: Sorted List, Dictionary
- Python XML: Expat, StartElementHandler
- Python Urllib Usage: Urlopen, UrlParse
- Python File Handling (with open, write)
- Python Example
- Python variables
- Python Random Numbers: randint, random.choice
- Python assert, O Option
- Python Data Types
- Python keywords
- Python literals
- Python MySQL Insert Operation
- Python MySQL Read Operation
- Python ascii Example
- Python ASCII Table Generator: chr
- Python Range: For Loop, Create List From Range
- Python re.match Performance
- Python re.match, search Examples
- Python Tkinter Menubutton
- Python Tkinter Menu
- Python Tkinter Message
- Python Tkinter Radiobutton
- Python List Examples
- Python Split String Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf