Overview of Python DateTime

One of the most basic requirements in programming is to inspect the execution time. And for the inspection, printing current time is usually the first task.

In Python language, there are several different alternatives, such as print(str(datetime.datetime.now())) which takes advantage of Python Object toString method.

To make a cheat-sheet for future reference, I decide to spend sometime to compose the summary of Python DateTime.

Overview

The datetime classes in Python are categorized into main 5 classes.

  • date – Manipulate just date ( Month, day, year)
  • time – Time independent of the day (Hour, minute, second, microsecond)
  • datetime – Combination of time and date (Month, day, year, hour, second, microsecond)
  • timedelta — A duration of time used for manipulating dates
  • tzinfo — An abstract class for dealing with time zones

-- Python DateTime, TimeDelta, Strftime(Format) with Examples

And there is also a time library for Timestamp.

Common Usages

today = datetime.date.today()
type(today) ## <class 'datetime.date'>
today ## datetime.date(2018, 5, 14)

today_weekday = datetime.date.weekday(today) ## Monday as 0 and Sunday as 6
type(today_weekday) ## <class 'int'>
today_weekday ## 0

now = datetime.datetime.now()
type(now) ## <class 'datetime.datetime'>
now ## datetime.datetime(2018, 5, 14, 23, 31, 24, 287790)

now_time = datetime.datetime.time(datetime.datetime.now())
type(now_time) ## <class 'datetime.time'>
now_time ## datetime.time(23, 32, 10, 543586)

time_string_formatted = now.strftime('%Y%m%d') ## and more
type(time_string_formatted) ## <class 'str'>
time_string_formatted ## '20180514'

## for Date object
Date.day, Date.month, Date.year
Date.weekday() ## 0 for Monday, 6 for Sunday

## for DateTime object
DateTime.hour, DateTime.minute, DateTime.second

Time Calculation

the_time_delta = datetime.timedelta(days=1, hours=1, minutes=1)
type(the_time_delta) ## <class 'datetime.timedelta'>
the_time_delta ## datetime.timedelta(1, 3660)

now_after_delta = now + the_time_delta
type(now_after_delta) ## <class 'datetime.datetime'>
now_after_delta ## datetime.datetime(2018, 5, 16, 0, 32, 24, 287790)

## for TimeDelta object
TimeDelta.days

Timestamp

import time

time.time() ## 1526312558.6715674

## more
time.localtime()

Screenshot

Selected Code Execution Result

References


* cached version, generated at 2019-06-22 12:11:32 UTC.

Subscribe by RSS