Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»General Articles»Current Date and Time in Python: In-Depth Tutorial

    Current Date and Time in Python: In-Depth Tutorial

    By RahulDecember 25, 20226 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 for getting the current date and time in Python, including using the built-in datetime module, the time module, and the dateutil module. We will also discuss how to format the date and time values as strings, and how to convert between timezones. Whether you are working with timestamps, scheduling tasks, or just want to display the current date and time in your Python program, this article will provide you with the tools you need.

    Advertisement

    Get Current Date & Time in Python

    We can use the `datetime`, `time`, and `dateutil` modules in Python to get the date and time.

    1. Using the `datetime` module
    2. One of the most popular ways to get the current date and time in Python is to use the datetime module. This module provides classes for working with dates, times, and timestamps.

      • 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 datetime.now() function returns a datetime object with the current date and time in the local timezone. The timezone is determined by the operating system on which the Python interpreter is running.

      • You can also specify a different timezone by passing a tzinfo argument to the datetime.now() function. For example, to get the current date and time in the UTC timezone, you can use the datetime.utcnow() function.

        1
        2
        3
        4
        import datetime
         
        current_datetime_utc = datetime.datetime.utcnow()
        print(current_datetime_utc)

      • You can also create a datetime object for a specific date and time by using the datetime() constructor. This constructor takes the year, month, day, hour, minute, second, and microsecond as arguments.

        1
        2
        3
        4
        import datetime
         
        specific_datetime = datetime.datetime(2022, 12, 25, 12, 0, 0)
        print(specific_datetime)

    3. Using the `time` module
    4. Another way to get the current date and time in Python is to use the time module. This module provides functions for working with time values.

      • To get the current date and time, you can use the time.gmtime() function, which returns a time structure representing the current date and time in the UTC timezone.

        1
        2
        3
        4
        import time
         
        current_time = time.gmtime()
        print(current_time)

      • You can also use the time.localtime() function to get the current date and time in the local timezone.

        1
        2
        3
        4
        import time
         
        current_local_time = time.localtime()
        print(current_local_time)

    5. Using the `dateutil` module
    6. Another option for getting the current date and time in Python is to use the dateutil module. This module provides functions for working with dates and times in a variety of formats and timezones.

      • To get the current date and time, you can use the dateutil.parser.parse() function, which parses a string representation of a date and time and returns a datetime object. To get the current date and time, you can pass the string “now” to this function.

        1
        2
        3
        4
        import dateutil.parser
         
        current_datetime = dateutil.parser.parse("now")
        print(current_datetime)

      • To get the current date and time in a specific timezone using the dateutil module, you can use the dateutil.tz.gettz() function to get a tzinfo object for that timezone, and then pass that object as the tz argument to the dateutil.parser.parse() function.

        For example, to get the current date and time in the Pacific Standard Time (PST) timezone, you can use the following code:

        1
        2
        3
        4
        5
        6
        import dateutil.parser
        import dateutil.tz
         
        pst_tz = dateutil.tz.gettz("PST")
        current_datetime_pst = dateutil.parser.parse("now", tz=pst_tz)
        print(current_datetime_pst)

      • You can also use the dateutil.tz.tzoffset() function to create a tzinfo object for a timezone with a fixed offset from UTC. For example, to get the current date and time in the Eastern Standard Time (EST) timezone, which is 5 hours behind UTC, you can use the following code:

        1
        2
        3
        4
        5
        6
        import dateutil.parser
        import dateutil.tz
         
        est_tz = dateutil.tz.tzoffset("EST", -5 * 60 * 60)
        current_datetime_est = dateutil.parser.parse("now", tz=est_tz)
        print(current_datetime_est)

    Formatting the date and time in Python

    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 format, you can use the %Y-%m-%d format string:

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

    • To get the current time as a string in the HH:MM:SS format, you can use the %H:%M:%S format string:

      1
      2
      3
      4
      5
      import datetime
       
      current_datetime = datetime.datetime.now()
      current_time = current_datetime.strftime("%H:%M:%S")
      print(current_time)

    • To get the current date and time as a string in the YYYY-MM-DD HH:MM:SS format, you can combine the %Y-%m-%d and %H:%M:%S format strings:

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

    • There are many other format strings available, which allow you to customize the output in various ways. For example, you can use the %I format string to get the hour in a 12-hour format with a leading zero for single-digit hours, and the %p format string to get the AM/PM indicator.

      1
      2
      3
      4
      5
      import datetime
       
      current_datetime = datetime.datetime.now()
      current_time_12h = current_datetime.strftime("%I:%M:%S %p")
      print(current_time_12h)

    You can find a full list of available format strings in the documentation for the strftime() method: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

    Converting Between Timezones in Python

    To convert a datetime object from one timezone to another using the dateutil module, you can use the dateutil.tz.gettz() function to get a tzinfo object for the target timezone, and then pass that object as the tz argument to the dateutil.parser.parse() function.

    • For example, to convert a datetime object from the Pacific Standard Time (PST) timezone to the Eastern Standard Time (EST) timezone, you can use the following code:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      import dateutil.parser
      import dateutil.tz
       
      pst_tz = dateutil.tz.gettz("PST")
      est_tz = dateutil.tz.gettz("EST")
       
      pst_datetime = dateutil.parser.parse("2022-12-25 12:00:00", tz=pst_tz)
      est_datetime = pst_datetime.astimezone(est_tz)
      print(est_datetime)

    • You can also use the dateutil.tz.tzoffset() function to create a tzinfo object for a timezone with a fixed offset from UTC. For example, to convert a datetime object from the UTC timezone to the Eastern Standard Time (EST) timezone, which is 5 hours behind UTC, you can use the following code:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      import dateutil.parser
      import dateutil.tz
       
      utc_tz = dateutil.tz.tzoffset("UTC", 0)
      est_tz = dateutil.tz.tzoffset("EST", -5 * 60 * 60)
       
      utc_datetime = dateutil.parser.parse("2022-12-25 12:00:00", tz=utc_tz)
      est_datetime = utc_datetime.astimezone(est_tz)
      print(est_datetime)

    • Note that the astimezone() method only works if the datetime object has a tzinfo attribute. If the datetime object does not have a tzinfo attribute, it is assumed to be in the local timezone. In this case, you can use the dateutil.parser.parse() function to create a new datetime object with a specific timezone, and then use the astimezone() method to convert it to another timezone.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      import dateutil.parser
      import dateutil.tz
       
      local_tz = dateutil.tz.gettz()
      est_tz = dateutil.tz.gettz("EST")
       
      local_datetime = datetime.datetime.now()
      est_datetime = dateutil.parser.parse(local_datetime.isoformat(), tz=local_tz).astimezone(est_tz)
      print(est_datetime)

    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.

    The time module provides functions for working with time values, such as the gmtime() and localtime() functions, which return a time structure representing the current date and time in the UTC and local timezones, respectively.

    The dateutil module provides additional tools for working with dates and times, such as the ability to parse date and time strings and convert between timezones.

    Once you have a datetime object, you can use the strftime() method to format the date and time values as strings, and the astimezone() method to convert the datetime object to a different timezone.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    sleep Command in Linux with Examples

    20 Basic Linux Commands for the Beginners (Recommended)

    tail Command in Linux with Examples

    Add A Comment

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • Test Your Internet Speed from the Linux Terminal
    • 11 Practical Example of cat Command in Linux
    • sleep Command in Linux with Examples
    • 20 Basic Linux Commands for the Beginners (Recommended)
    • tail Command in Linux with Examples
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

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