Datetime data is commonly used in analysis. However, it is a special data type that has it's own calculation and other rules. In this article, I am going to introduce handing this type of data using Python.

  1. time module

Python has a in-built library "time". It is a good tool to manipulate time data type. Let's see some basic methods:

import time
print("time(): {}".format(time.time()))  # The number type of local time.
print("ctime(): {}".format(time.ctime())) # A string type of local time.
print("asctime(): {}".format(time.asctime())) # A string type of local time. Can be a parameter of struct_time for transfer.
print("localtime(): {}".format(time.localtime())) #Returns a struct_time type of local time.
print("gmtime(): {}".format(time.gmtime())) #Returns a struct_time type of local time in UTC timezone.
None

As you see, struct_time is a special type that contains 9 elements. Of which the first 6 are year, month, day, hour, minute and second, respectively. Besides:

tm_wday means day of week (Sunday = 0)

tm_yday means day of year

tm_isdst means if it is summer time

time.strftime() is able to transfer a struct_time data to a string. It has some designated formats:

%c: local date and time

%x: local date

%X: local time

%y: 2 digits of the year

%Y: 4 digits of the year

%m: month (01–12)

%b: month short name

%B: month full name

%d: day of month (01–31)

%j: day of year (001–366)

%U: week of year (00–53, starts with Sunday)

%W: week of year (00–53, starts with Monday)

%w: day of week (0–6)

%a: week short name

%A: week full name

%H: hour of day (00–23)

%I: hour of day (01–12)

%p: am / pm while using %I

%M: minute (00–59)

%S: second (01–61, the leap year seconds = 2 seconds)

%Z: timezone

The syntax is:

time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
None

On the contrary, time.strptime() can transfer a string type of time to struct_time format:

time.strptime(time.ctime())
None

time.sleep() provides a break time for the script. The parameter is a number of second:

print(time.ctime())
time.sleep(5)
print(time.ctime())
None

2. datetime module

datetime module is like a higher level of time module. It contains the following classes:

date: includes year, month and day

time: includes hour, minute, second and microsecond

datetime: represents date and time

timedelta: calculate the distance of 2 datetimes

tzinfo: for timezone information

(1) date

We can see some attributes of date class:

from datetime import date
import time

print('date.max:', date.max)     # The maximum date in the date class
print('date.min:', date.min)     # The minimum date in the date class
print('date.resolution:', date.resolution)   # The lowest level unit of the date class (day)
print('date.today():', date.today())     # Today's date
None

Here are some commonly used methods:

from datetime import date
today = date.today()
print('today:', today)                               # Today's date
print('.year:', today.year)                          # Year number
print('.month:', today.month)                        # Month number
print('.replace():', today.replace(year=2017) )      # Replace the date element
print('.weekday():', today.weekday())                # Weekday number, Monday = 0
print('.isoweekday():', today.isoweekday())          # ISO weekday number, Monday = 1
print('.isocalendar():', today.isocalendar())        # ISO calendar format
print('.isoformat():', today.isoformat())            # Returns a YYYY-MM-DD format
print('.strftime():', today.strftime('%Y-%m-%d') )   # Transfer a date to string data type
print('.toordinal():', today.toordinal())            # Returns a Gregorian Calendar date
None

datetime provides an easy way to calculate and compare dates like:

date2 = date1 + timedelta # Adding a date unit
date2 = date1 - timedelta # Substracting a date unit
td = date1 - date2 # Returns a timedelta
date1 < date2 C    # Compare 2 dates

To be continued…