python logo

Python Commandments

Current date and time in Python

The module time and locale can be used to get current date and time in Python. The time module provides various functions for operating time.
An alternative is using the datetime module.

locale date

The time module lets you use time in Python, it’s part of the Python standard library so you don’t need to manually install it.

You can get the current date (year,month,date) using the code below:

def get_current_date():
    import time
    import locale
    return time.strftime('%Y-%m-%d')

This outputs:

>>> get_current_date()
‘2019-03-19’

locale time

To get the current date and time, use the code below

def get_current_time():
    import time
    import locale
    return time.strftime('%Y-%m-%d %H:%M:%S')

This outputs:

>>> get_current_time()
‘2019-03-19 07:09:07’
current date and time in python

datetime

The datetime module can be used too.
You can use the datetime module to get the current date and time:

>>> from datetime import *
>>> import time
>>> 
>>> print(datetime.today())

This outputs in this style:

2020-06-04 17:07:19.092635

datetime returns a structure, which contains time.hour, time.minute, time.second, time.microsecond.

>>> tm = datetime.now()
>>> print(f" {tm.hour}:{tm.minute}:{tm.second}")

It also contains time.year, time.month, time.year

>>> print(f" {tm.year}:{tm.month}:{tm.day}")

So you can do this:

>>> from datetime import *
>>> import time
>>> tm = datetime.now()
>>> year = tm.year
>>> month = tm.month
>>> day = tm.day
>>> hour = tm.hour
>>> minute = tm.minute
>>> second = tm.second
>>> 
>>> print(year)
2020
>>> print(month)
6
>>> print(day)
4
>>> print(hour)
17
>>> print(minute)
10
>>> print(second)
33

The available tiypes in datetime are year,month,day,hour,minute,second,microsecond and tzinfo.