Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Mastering Python datetime: Practical Guide to Dates, Times, and Timezones

Mastering Python datetime

Discover how to work with dates and times in Python through hands‑on examples and clear explanations.

Video: Python datetime – Work with Dates and Times

Python’s datetime module provides powerful tools for manipulating dates and times. Below we walk through common tasks, from retrieving the current moment to formatting and timezone handling.


Example 1: Get Current Date and Time

import datetime

datetime_object = datetime.datetime.now()
print(datetime_object)

The output will look like:

2018-12-19 09:26:03.478039

Here we import the module with import datetime. The datetime class contains a now() method that returns the local date and time.


Example 2: Get Current Date

import datetime

date_object = datetime.date.today()
print(date_object)

The output will be:

2018-12-19

We use today() from the date class to obtain the current calendar date.


Exploring the datetime module

Run dir(datetime) to list all attributes and classes:

import datetime

print(dir(datetime))

Output:

['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_divide_and_round', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']

Key classes include date, time, datetime, and timedelta.


datetime.date Class

The date class represents a calendar date (year, month, day).


Example 3: Create a Date Object

import datetime

d = datetime.date(2019, 4, 13)
print(d)

Result:

2019-04-13

Here date() is a constructor that accepts year, month, and day as arguments.

The variable a is a date instance.


Importing only the date class:

from datetime import date

a = date(2019, 4, 13)
print(a)

Example 4: Current Date

Use the today() classmethod:

from datetime import date

today = date.today()
print("Current date =", today)

Example 5: From Timestamp

A Unix timestamp counts seconds since 1970‑01‑01 UTC. Convert it with fromtimestamp():

from datetime import date

timestamp = date.fromtimestamp(1326244364)
print("Date =", timestamp)

Output:

Date = 2012-01-11

Example 6: Access Year, Month, Day

from datetime import date

today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)

datetime.time

The time class stores a clock time without a date.


Example 7: Create Time Objects

from datetime import time

a = time()
print("a =", a)

b = time(11, 34, 56)
print("b =", b)

c = time(hour=11, minute=34, second=56)
print("c =", c)

d = time(11, 34, 56, 234566)
print("d =", d)

Result:

a = 00:00:00
b = 11:34:56
c = 11:34:56
d = 11:34:56.234566

Example 8: Inspect Time Components

from datetime import time

a = time(11, 34, 56)

print("hour =", a.hour)
print("minute =", a.minute)
print("second =", a.second)
print("microsecond =", a.microsecond)

Output:

hour = 11
minute = 34
second = 56
microsecond = 0

datetime.datetime

The datetime class combines both date and time information.


Example 9: Create a Datetime Object

from datetime import datetime

# year, month, day
A = datetime(2018, 11, 28)
print(A)

# full specification
B = datetime(2017, 11, 28, 23, 55, 59, 342380)
print(B)

Result:

2018-11-28 00:00:00
2017-11-28 23:55:59.342380

Year, month, and day are mandatory; hour, minute, second, and microsecond default to zero.


Example 10: Inspect Components & Timestamp

from datetime import datetime

A = datetime(2017, 11, 28, 23, 55, 59, 342380)
print("year =", A.year)
print("month =", A.month)
print("day =", A.day)
print("hour =", A.hour)
print("minute =", A.minute)
print("timestamp =", A.timestamp())

Output:

year = 2017
month = 11
day = 28
hour = 23
minute = 55
timestamp = 1511913359.34238

datetime.timedelta

A timedelta object represents a duration between two dates or times.


Example 11: Difference Between Dates & Times

from datetime import datetime, date

T1 = date(year=2018, month=7, day=12)
T2 = date(year=2017, month=12, day=23)
T3 = T1 - T2
print("T3 =", T3)

T4 = datetime(year=2018, month=7, day=12, hour=7, minute=9, second=33)
T5 = datetime(year=2019, month=6, day=10, hour=5, minute=55, second=13)
T6 = T4 - T5
print("T6 =", T6)

print("type of T3 =", type(T3))
print("type of T6 =", type(T6))

Output:

T3 = 201 days, 0:00:00
T6 = -333 days, 1:14:20
type of T3 = <class 'datetime.timedelta'>
type of T6 = <class 'datetime.timedelta'>

Example 12: Subtracting Timedelta Objects

from datetime import timedelta

T1 = timedelta(weeks=2, days=5, hours=1, seconds=33)
T2 = timedelta(days=4, hours=11, minutes=4, seconds=54)
T3 = T1 - T2
print("T3 =", T3)

Output:

T3 = 14 days, 13:55:39

Example 13: Negative Timedelta

from datetime import timedelta

T1 = timedelta(seconds=33)
T2 = timedelta(seconds=54)
T3 = T1 - T2
print("T3 =", T3)
print("abs(T3) =", abs(T3))

Output:

T3 = -1 day, 23:59:39
abs(T3) = 0:00:21

Example 14: Total Seconds in a Timedelta

from datetime import timedelta

T = timedelta(days=5, hours=1, seconds=33, microseconds=233423)
print("total seconds =", T.total_seconds())

Output:

total seconds = 435633.233423

You can add dates, multiply a timedelta by a number, and divide it by a float to scale durations.


Formatting and Parsing Dates

Different locales use varied date formats (e.g., mm/dd/yyyy in the US vs dd/mm/yyyy in the UK). Python’s strftime() and strptime() methods help convert between datetime objects and formatted strings.


Python strftime() – datetime to string

from datetime import datetime

now = datetime.now()

# Hour:minute:second
T = now.strftime("%H:%M:%S")
print("time:", T)

# US format
S1 = now.strftime("%m/%d/%Y, %H:%M:%S")
print("S1:", S1)

# UK format
S2 = now.strftime("%d/%m/%Y, %H:%M:%S")
print("S2:", S2)

Typical output:

time: 04:34:52
S1: 12/26/2018, 04:34:52
S2: 26/12/2018, 04:34:52

Common format codes: %Y year, %m month, %d day, %H hour, %M minute, %S second.


Python strptime() – string to datetime

from datetime import datetime

date_string = "21 June, 2018"
print("date_string =", date_string)

date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)

Output:

date_string = 21 June, 2018
date_object = 2018-06-21 00:00:00

Here %d is day, %B full month name, and %Y year.


Timezone Awareness

For applications that must display or compute times in different zones, avoid manual calculations and use the pytz library.

from datetime import datetime
import pytz

local = datetime.now()
print("Local:", local.strftime("%m/%d/%Y, %H:%M:%S"))

tz_NY = pytz.timezone('America/New_York')
dt_NY = datetime.now(tz_NY)
print("NY:", dt_NY.strftime("%m/%d/%Y, %H:%M:%S"))

tz_London = pytz.timezone('Europe/London')
dt_London = datetime.now(tz_London)
print("London:", dt_London.strftime("%m/%d/%Y, %H:%M:%S"))

Sample output:

Local: 12/20/2018, 13:10:44
NY: 12/20/2018, 08:10:44
London: 12/20/2018, 13:10:44

The datetime_NY and datetime_London objects contain timezone‑aware timestamps.


Python

  1. Mastering Python Data Types: A Practical Guide
  2. Mastering Python Operators: A Comprehensive Guide
  3. Mastering Python's While Loop: Syntax, Examples, and Best Practices
  4. Python List Operations: Creation, Access, Modification, and Advanced Techniques
  5. Mastering Python Tuples: Creation, Access, and Advanced Operations
  6. Mastering Python Dictionaries: Creation, Manipulation, and Advanced Techniques
  7. Retrieve Current Date and Time in Python: A Practical Guide
  8. Python: Retrieve Current Time and Timezone Data with Ease
  9. Mastering Python’s datetime Module: Dates, Times, Timedelta & Strftime Explained
  10. Mastering Dates & Times in Python: A Practical Guide