Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»Programming»Python»How to Get Current Date & Time in Python

    How to Get Current Date & Time in Python

    By RahulDecember 26, 20225 Mins Read

    Getting the current date and time is a common task in Python programming. There are several ways to do this, depending on your needs and the libraries you have available. In this article, we will explore some of the most common methods used by developers for getting the current date and time in Python, including using the built-in datetime module.

    Advertisement

    To understand more about it, visit our in-depth Python date time tutorial.

    Get Current Date & Time in Python

    To get the current date and time, you can use the `datetime.now()` function, which returns a datetime object representing the current date and time in the local timezone.

    1
    2
    3
    4
    import datetime
     
    current_datetime = datetime.datetime.now()
    print(current_datetime)

    The above script will output the following:

    2022-12-25 18:13:13.363653
    

    To format the date and time in a specific way, you can use the `strftime()` method of the datetime object, which takes a format string as an argument. The format string specifies how the date and time values should be formatted.

    For example, to get the current date as a string in the `YYYY-MM-DD HH:MM:SS` format, you can use the `%Y-%m-%d %H:%M:%S` format string:

    1
    2
    3
    4
    5
    import datetime
     
    current_datetime = datetime.datetime.now()
    current_date = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
    print(current_date)

    The above script will output the following:

    2022-12-25 18:15:03
    

    Python `datetime` Module Class Attributes

    The datetime module in Python provides classes for working with dates, times, and timestamps. The main class is datetime, which represents a single point in time.

    Here are some common attributes of the datetime class:

    • `year`: the year (four digits)
    • `month`: the month (1-12)
    • `day`: the day of the month (1-31)
    • `hour`: the hour of the day (0-23)
    • `minute`: the minute of the hour (0-59)
    • `second`: the second of the minute (0-59)
    • `microsecond`: the microsecond of the second (0-999999)
    • `tzinfo`: an object representing the time zone

    Here is an example of creating a datetime object and accessing its attributes:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    from datetime import datetime
     
    dt = datetime(2022, 12, 31, 23, 59, 59)
    ## Uncomment below to get the current date and time
    #dt = datetime.now()
     
    dt = datetime.now()
    print(dt.year)  # prints 2022
    print(dt.month)  # prints 12
    print(dt.day)  # prints 31
    print(dt.hour)  # prints 23
    print(dt.minute)  # prints 59
    print(dt.second)  # prints 59
    print(dt.microsecond)  # prints 0
    print(dt.tzinfo)  # prints None

    Get Formated Date Time in Python

    To get a formatted date and time string in Python, you can use the `strftime` method of the `datetime` class.

    Here is an example of using `strftime` to get a formatted date and time string:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    from datetime import datetime
     
    # Create a datetime object
    dt = datetime(2022, 12, 31, 23, 59, 59)
    ## Uncomment below to get the current date and time
    #dt = datetime.now()
     
    # Use strftime to create a formatted string
    formatted_date = dt.strftime("%Y-%m-%d %H:%M:%S")
    print(formatted_date)  # prints "2022-12-31 23:59:59"

    The `strftime` method takes a format string as its argument, which specifies how the date and time should be formatted. In the example above, the format string “%Y-%m-%d %H:%M:%S” specifies that the year should be formatted as a four-digit number (`%Y`), the month as a two-digit number (`%m`), the day as a two-digit number (`%d`), the hour as a two-digit number (`%H`), the minute as a two-digit number (`%M`), and the second as a two-digit number (`%S`).

    You can use different format codes to customize the output of `strftime` to your liking. For example, you can use `%A` to get the full name of the day of the week, `%B` to get the full name of the month, and `%I` to get the hour in 12-hour format with a leading zero for single-digit hours.

    Here is a few more examples of strftime format codes:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    from datetime import datetime
     
    # Create a datetime object
    dt = datetime(2022, 12, 31, 23, 59, 59)
    ## Uncomment below to get the current date and time
    #dt = datetime.now()
     
    # Use strftime to create a formatted string
    print(dt.strftime("%Y-%m-%d %H:%M:%S"))  # prints 2022-12-31 23:59:59
    print(dt.strftime("%Y/%m/%d"))  # prints 2022/12/31
    print(dt.strftime("%H:%M:%S"))  # prints 23:59:59
    print(dt.strftime("%I:%M:%S %p"))  # prints 11:59:59 PM
    print(dt.strftime("%a, %b %d, %Y"))  # prints Sat, Dec 31, 2022
    print(dt.strftime("%a, %b %d, %Y %H:%M:%S"))  # prints Sat, Dec 31, 2022 23:59:59
    print(dt.strftime("%a %b %d %H:%M:%S %Y"))  # prints Sat Dec 31 23:59:59 2022
    print(dt.strftime("%A, %B %d, %Y %I:%M %p"))  # prints Saturday, December 31, 2022 11:59 PM"

    Below is the list of directives that can be used to format date and time output in your Python script.

    DirectiveMeaning
    %aLocale’s abbreviated weekday name.
    %ALocale’s full weekday name.
    %bLocale’s abbreviated month name.
    %BLocale’s full month name.
    %cLocale’s appropriate date and time representation.
    %dDay of the month as a decimal number [01,31].
    %HHour (24-hour clock) as a decimal number [00,23].
    %IHour (12-hour clock) as a decimal number [01,12].
    %jDay of the year as a decimal number [001,366].
    %mMonth as a decimal number [01,12].
    %MMinute as a decimal number [00,59].
    %pLocale’s equivalent of either AM or PM.
    %SSecond as a decimal number [00,61].
    %UWeek number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.
    %wWeekday as a decimal number [0(Sunday),6].
    %WWeek number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
    %xLocale’s appropriate date representation.
    %XLocale’s appropriate time representation.
    %yYear without century as a decimal number [00,99].
    %YYear with century as a decimal number.
    %zTime zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].
    %ZTime zone name (no characters if no time zone exists).
    %%A literal '%' character.

    I hope these examples have helped you understand how to get the current date and time in Python, and how to convert between timezones.

    Conclusion

    In summary, the datetime module is a convenient and powerful tool for working with dates, times, and timestamps in Python. You can use the datetime.now() function to get the current date and time in the local timezone, or the datetime.utcnow() function to get the current date and time in the UTC timezone. You can also use the datetime() constructor to create a datetime object for a specific date and time.

    date date and time Python time
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    How to Create and Read List in Python

    What are the Python Static Variables

    Python Program to Add Two Numbers

    View 4 Comments

    4 Comments

    1. Tuhin Mitra on June 26, 2019 4:18 pm

      content is Very helpful sir !

      Reply
    2. Pruthvi Shrikaanth on May 21, 2019 8:25 pm

      Thnx, very helpful!

      Reply
    3. Sonam on May 4, 2019 6:33 am

      Every nicely explianed!

      Reply
    4. John Doe on June 30, 2018 1:20 pm

      Thank you!

      Reply

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • Configure Postfix to Use Gmail SMTP on Ubuntu & Debian
    • PHP Arrays: A Beginner’s Guide
    • Deploying Flask Application on Ubuntu (Apache+WSGI)
    • OpenSSL: Working with SSL Certificates, Private Keys and CSRs
    • How to Create and Read List in Python
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.