How To Use Python Time, DateTime Module Examples

Python provides a variety of time and date processing methods, mainly in time and datetime modules. In this article i will show you some time and datetime module examples to tell you how to use them in python.

1. Python Represents Time In Two Ways.

1.1 Timestamp.

The timestamp is relative to the offset in seconds from 1970.1.1 00:00:00. Timestamp is unique.

1.2 Struct Time Tuple.

Struct time is a tuple of time elements, struct_time tuple has nine elements, which are defined as follows. Please note struct_time for the same timestamp varies depending on the time zone.

  1. tm_year : This element represent year. It is four digits, for example : 2019.
  2. tm_mon : Represent month, two digits, for example : 03, value range is 1 – 12.
  3. tm_mday : Represent day in month, two digits, for example : 29, value range is 1 – 31.
  4. tm_hour : Represent hour in a day, two digits, for example : 19, value range is 0 – 24.
  5. tm_min : Represent minutes, for example 19, value range 0 – 59.
  6. tm_sec : Represent seconds, for example 19, value range 0 – 59.
  7. tm_wday : Day of the week, for example 0 means sunday, value range is 0 – 6.
  8. tm_yday : Day of the year, value range is 1 – 366.
  9. tm_isdst : Represent daylight saving time, default value is -1.

2. Python time Module.

In Python documentation, time is classified in the Generic Operating System Services. In other words, it provides functions closer to the Operating System level. As you can see from the documentation, the time module is built around Unix Timestamp. This module mainly includes a class struct_time, along with several other functions and related constants.

It is important to note that most functions in time module will invoke same name function of the os platform C library, so that some functions are platform specific, so same name function may have different effects on different os platform.

Another point is that because it is based on Unix Timestamp, the range of date it can express is limited to 1970-2038. If you’re writing code that deals with dates that are outside the scope, you had better consider using the datetime module.

2.1  Python time Module Methods.

  1. Before invoke any time module methods, you should first import time module.
    import time
  2. time.sleep(secs) : Delay the specified time (seconds) and continue running.
    >>> for i in range(10):
    ...    print(i)
    ...    time.sleep(2)
    ... 
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>> 
    
  3. time.localtime([secs]) : Convert a timestamp to a struct_time of the current time zone. If secs parameter is not provided, then use current time seconds.
    >>> time.localtime(time.time())
    time.struct_time(tm_year=2019, tm_mon=3, tm_mday=29, tm_hour=16, tm_min=24, tm_sec=9, tm_wday=4, tm_yday=88, tm_isdst=0)
  4. time.strftime(format[, t]) : Return the specified struct_time t’s string value ( t’s default value is current time if t is not provided) according to the specified time string format.
    >>> time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    '2019-03-29 16:25:13'
    
  5. time.time() : Returns the timestamp of the current time.
    >>> time.time()
    1553847582.5042903
  6. time.mktime(t) : Convert a time.struct_time to a timestamp. This method is opposite to time.localtime() which receives a timestamp and returns a struct_time.
    >>> s_t = time.localtime(1000000000)
    >>> s_t
    time.struct_time(tm_year=2001, tm_mon=9, tm_mday=9, tm_hour=9, tm_min=46, tm_sec=40, tm_wday=6, tm_yday=252, tm_isdst=0)
    >>> time.mktime(s_t)
    1000000000.0
    
  7. time.gmtime([secs]) : Similar to the time.localtime() method, the gmtime() method convert a timestamp to a UTC time zone (0 time zone) based time.struct_time object.
    >>> time.gmtime(time.time())
    time.struct_time(tm_year=2019, tm_mon=3, tm_mday=29, tm_hour=8, tm_min=41, tm_sec=6, tm_wday=4, tm_yday=88, tm_isdst=0)
  8. time.clock() : It should be noted that this method returned value means different in different operating system. On UNIX systems, it returns “process time,” which is a floating point number in seconds (timestamp). In WINDOWS, the first call returns the actual running time of the process. The second subsequent call is the elapsed time since the first call.
    >>> time.clock()
    __main__:1: DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead
    0.094425
    
  9. time.asctime([t]) : Convert a tuple or struct_time object which represent time to a string form like ‘Fri Mar 29 19:11:31 2019’.
    >>> time.asctime()
    'Fri Mar 29 19:11:31 2019'
    
  10. time.ctime([secs]) : Converts a timestamp (a floating point number in seconds) to a string form like ‘Fri Mar 29 19:21:37 2019’.
    >>> time.ctime()
    'Fri Mar 29 19:21:37 2019'

3. Python datetime Module.

Datetime is a lot more advanced than time, you can think datetime module extends time module, datetime module provides more practical functions. The datetime module contains several classes, list as follows.

  1. timedelta : Mainly used to calculate the time span.
  2. tzinfo :  Provide methods of time zone related.
  3. time : Provide time related methods only.
  4. date : Provide date related methods only.
  5. datetime : Provide both date and time operation methods.

The most used class in above list is datetime.datetime and datetime.timedelta. The other two, datetime.date and datetime.time, are not very different from datetime.datetime.

3.1 datetime.datetime class properties and methods.

  1. datetime.year, datetime.month, datetime.day, datetime.hour, datetime.minute, datetime.second, datetime.microsecond : You can understood all these datetime.datetime class’s properties by the word literal meaning.
    Run below command in a terminal python3 interactive console.
    
    >>> import datetime
    >>> 
    >>> dt = datetime.datetime.now()
    
    >>> dt.year
    2019
    
    >>> dt.month
    3
    
    >>> dt.day
    29
    
    >>> dt.hour
    19
    
    >>> dt.minute
    59
    
    >>> dt.seconds
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'datetime.datetime' object has no attribute 'seconds'
    
    >>> dt.second
    29
    
    >>> dt.microsecond
    14285
    
  2. datetime.now([tz]) : Return current time datetime object by timezone. tz is None or a datetime.tzinfo class’s instance.
  3. datetime.today() : Return current time datetime object according to local timezone.
  4. datetime.utcnow() : Return current time datetime object according to UTC timezone.
  5. datetime.fromtimestamp(timestamp[, tz]) : Built datetime object by unix timestamp.
  6. datetime.date() : Return date object.
  7. datetime.time() : Return time object.
  8. datetime.replace(name=value) : By default, datetime properties value is read-only, but you can use this method to replace date property values.
    >>> dt = datetime.datetime.now # do not forget () after the method, otherwise you will get below information.
    >>> dt
    <built-in method now of type object at 0x7f2c6b348ca0>
    >>> 
    >>> 
    >>> dt = datetime.datetime.now()
    
    >>> dt
    datetime.datetime(2019, 3, 29, 20, 42, 48, 689605)
    
    >>> dt1 = dt.replace(year=2018)
    
    >>> dt1
    datetime.datetime(2018, 3, 29, 20, 42, 48, 689605)
    
    >>> dt
    datetime.datetime(2019, 3, 29, 20, 42, 48, 689605)
    

Below is an example about using above methods.

>>> import datetime

>>> dt_now = datetime.datetime.now()
>>> dt_now
datetime.datetime(2019, 3, 29, 20, 9, 50, 454469)

>>> dt_now.strftime('%Y-%m-%d %H:%M:%S')
'2019-03-29 20:09:50'

>>> dt_delta = datetime.timedelta(hours=24)

>>> print(dt_now + dt_delta)
2019-03-30 20:09:50.454469

>>> print(dt_now - dt_delta)
2019-03-28 20:09:50.454469