How To Get The Current Date Time In Python

1. How to get the current system date time in python.

  1. Import the python datetime module.
    >>> import datetime
  2. Get the current date time.
    >>> curr_time = datetime.datetime.now()
    >>> 
    >>> curr_time.year
    2021
    >>> curr_time.month
    4
    >>> curr_time.day
    5
    >>> curr_time.hour
    19
    >>> curr_time.minute
    54
    >>> curr_time.second
    22
    >>> curr_time.date()
    datetime.date(2021, 4, 5)

2. How to convert python datetime value to a formatted string and vice versa.

  1. The function datetime.datetime.now() returned datetime string format is ( yyyy, month, day, hour, minute, second, millisecond ).
    >>> datetime.datetime.now()
    datetime.datetime(2021, 4, 5, 19, 59, 10, 165964)
  2. We can use the python function strftime() to convert the datetime value to the formatted string that we want.
    >>> curr_time = datetime.datetime.now()
    >>> 
    >>> curr_time.strftime("%Y-%m-%d")
    '2021-04-05'
    >>> 
    >>> curr_time.strftime("%m/%d")
    '04/05'
  3. Convert python datetime value to string example.
    >>> curr_time = datetime.datetime.now()
    >>> 
    >>> datetime.datetime.strftime(curr_time,'%Y-%m-%d %H:%M:%S')
    '2021-04-05 20:05:33'
  4. Convert python datetime string to datetime example.
    >>> import datetime
    >>>
    >>> time_str = '2021-06-06 15:59:58'
    >>> 
    >>> datetime.datetime.strptime(time_str,'%Y-%m-%d %H:%M:%S')
    datetime.datetime(2021, 6, 6, 15, 59, 58)
    >>> 
    

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.