get-current-date-and-time-in-python

Response: To retrieve the current time in Python, you may utilize the datetime.now() function.

Obtaining the present time is crucial for purposes such as documenting timestamps, logging events, or scheduling tasks within a program. This article will examine various techniques available for acquiring the current time in Python.

Contents Overview:

Approaches to Retrieve the Current Time in Python

Python offers specific functions to output the current time. Let’s delve into these functions to retrieve the current time with illustrative examples:

Approach 1: Employing the datetime.now() Function in Python

The datetime.now() function facilitates printing the moment of program execution. It allows us to showcase the precise time at which the code was compiled.

Example:

Python

Code Copied!

var isMobile = window.innerWidth { jQuery(“.maineditor1681 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor1681 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode1681() { var code = editor1681.getSession().getValue(); jQuery(“#runBtn1681 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “python”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output1681”).html(“

" + data + "

“); jQuery(“.maineditor1681 .code-editor-output”).show(); jQuery(“#runBtn1681 i.run-code”).hide(); } }) }

function closeoutput1681() { jQuery(“.maineditor1681 .code-editor-output”).hide(); }

// Attach event listeners to the buttons document.getElementById(“copyBtn1681”).addEventListener(“click”, copyCodeToClipboard1681); document.getElementById(“runBtn1681”).addEventListener(“click”, runCode1681); document.getElementById(“closeoutputBtn1681”).addEventListener(“click”, closeoutput1681);

Within this code, the format of the time displayed can be modified; for instance, if you wish to present the minutes first, adjust the format to “%M:%H:%S”. Similarly, you can vary the format of the time shown.

Output:

datetime.now() Function in Python Output

1. Utilizing attributes of the datetime.now() function

Several attributes such as day, month, year, minute, seconds, and hour can be displayed. Based on these attributes, here is an example:

Illustration:

Python

Code Duplicated!

var isMobile = window.innerWidth { jQuery(“.maineditor64635 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor64635 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error duplicating code: “, err); }); }

function runCode64635() { var code = editor64635.getSession().getValue(); jQuery(“#runBtn64635 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “python”, code: code, cmd_line_args: “”, variablenames: “”, action: “compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output64635”).html(“

"+data+"");
            jQuery(".maineditor64635 .code-editor-output").show();
            jQuery("#runBtn64635 i.run-code").hide();
        }
    });
}

function closeoutput64635() {	
    var code = editor64635.getSession().getValue();
    jQuery(".maineditor64635 .code-editor-output").hide();
}

// Add event listeners to the buttons
document.getElementById("copyBtn64635").addEventListener("click", copyCodeToClipboard64635);
document.getElementById("runBtn64635").addEventListener("click", runCode64635);
document.getElementById("closeoutputBtn64635").addEventListener("click", closeoutput64635);


Outcome:

Output of datetime.now() method

2. Utilizing pytz along with datetime library in datetime.now() function

In the previous instance, we were only able to view the date, time, hour, and minutes, but it failed to indicate the location or the timezone. To display the timezone along with the date and time, we need a timezone-aware library named ‘pytz’.

Illustration:

Python
Code Duplicated!
```html i.run-code").show(); jQuery(".output-tab").click(); jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1]; jQuery(".output19740").html("
"+data+"");
									jQuery(".maineditor19740 .code-editor-output").show();
									jQuery("#runBtn19740 i.run-code").hide();
									
								}
							})
					

						}
						
						
		function closeoutput19740() {	
		var code = editor19740.getSession().getValue();
		jQuery(".maineditor19740 .code-editor-output").hide();
		}

    // Attach event listeners to the buttons
    document.getElementById("copyBtn19740").addEventListener("click", copyCodeToClipboard19740);
    document.getElementById("runBtn19740").addEventListener("click", runCode19740);
    document.getElementById("closeoutputBtn19740").addEventListener("click", closeoutput19740);
 
    



Result:

Output of datetime.now() method

3. Show UTC Date and Time utilizing utcnow() method

The acronym UTC represents Coordinated Universal Time; this UTC assists users worldwide in logging the user time.

Sample:

Python
Code Copied!

Result:

Mastering Date and Time Retrieval in Python

Method 2: Employing time() module to Show the Current Time in Python

To obtain the current time, we can utilize the time module in Python, and then the functions such as time.gmtime() or time.localtime() for retrieving time in UTC or local time, respectively.

Sample:

Python
Code Copied!

Result:

Mastering Date and Time Retrieval in Python

1. To Display Current Time In GMT Format

The abbreviation GMT stands for Greenwich Mean Time. To obtain the current time in GMT format using the time module, we utilize time.gmtime(), which returns the time in UTC.

Illustration:

Python
Code Successfully Copied!

In this illustration, you can observe that time.gmtime() returns the time in UTC, while time.strftime(‘%a, %d %b %Y %H:%M:%S GMT’, current_time_gmt) formats the time to appear as: Day, DD Month YYYY HH:MM:SS GMT.

Result:

``````html Mastering Date and Time Retrieval in Python

2. To Present the Current Time in ISO Format:

Similarly to the prior example, we can derive an ISO format of the time using iso_format_time. Below is an illustration:

Illustration:

Python
Code Copied!

"); jQuery(".maineditor46205 .code-editor-output").show(); jQuery("#runBtn46205 i.run-code").hide(); } }); }

function closeoutput46205() { jQuery(".maineditor46205 .code-editor-output").hide(); }

// Setting up event listeners for the buttons document.getElementById("copyBtn46205").addEventListener("click", copyCodeToClipboard46205); document.getElementById("runBtn46205").addEventListener("click", runCode46205); document.getElementById("closeoutputBtn46205").addEventListener("click", closeoutput46205);

Within this illustration, the time has been transformed from GMT to ISO.

Result:

Mastering Date and Time Retrieval in Python

3. To Reveal milliseconds in time()

Now, let’s attempt to present the current time inclusive of milliseconds utilizing the time module. You can employ time.time() to retrieve the current time in seconds and subsequently format it to comprise milliseconds.

Illustration:

Python

Code Copied!

var isMobile = window.innerWidth { jQuery(".maineditor32180 .copymessage").show(); setTimeout(function() { jQuery(".maineditor32180 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Unable to copy code: ", err); }); }

function runCode32180() { var code = editor32180.getSession().getValue();

jQuery("#runBtn32180 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", // Additional parameters needed here ``````html "post",

data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output32180").html("

"+data+"");
									jQuery(".maineditor32180 .code-editor-output").show();
									jQuery("#runBtn32180 i.run-code").hide();

} })

}

function closeoutput32180() { var code = editor32180.getSession().getValue(); jQuery(".maineditor32180 .code-editor-output").hide(); }

// Bind event listeners to the buttons document.getElementById("copyBtn32180").addEventListener("click", copyCodeToClipboard32180); document.getElementById("runBtn32180").addEventListener("click", runCode32180); document.getElementById("closeoutputBtn32180").addEventListener("click", closeoutput32180);

Output:

Mastering Date and Time Retrieval in Python

4. Displaying Nanoseconds in time()

To represent nanoseconds utilizing the time module, you can leverage time.time() for seconds; however, it does not directly yield nanoseconds. For accurate time tracking with nanosecond resolution, the time module provides time_ns(), which delivers the current time in nanoseconds.

Example:

Python

Code Copied!

var isMobile = window.innerWidth { // alert("Code copied to clipboard!");

jQuery(".maineditor34005 .copymessage").show(); setTimeout(function() { jQuery(".maineditor34005 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode34005() {

var code = editor34005.getSession().getValue();

jQuery("#runBtn34005 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output34005").html("

"+data+"");
									jQuery(".maineditor34005 .code-editor-output").show();
									jQuery("#runBtn34005 i.run-code").hide();

} })

}

function closeoutput34005() { var code = editor34005.getSession().getValue(); jQuery(".maineditor34005 .code-editor-output").hide(); }

// Bind event listeners to the buttons document.getElementById("copyBtn34005").addEventListener("click", copyCodeToClipboard34005); document.getElementById("runBtn34005").addEventListener("click", runCode34005); document.getElementById("closeoutputBtn34005").addEventListener("click", closeoutput34005);

Output:

Mastering Date and Time Retrieval in Python

Method 3: Utilizing strftime() method to Present the Current Time in Python

Although strftime() does not inherently accommodate nanoseconds, you can format the time using milliseconds from datetime, and it is possible to append nanoseconds manually if necessary.

Example:

Python

Code Copied!

var isMobile = window.innerWidth { // alert("Code copied to clipboard!");

jQuery(".maineditor34474 .copymessage").show(); setTimeout(function() { jQuery(".maineditor34474 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode34474() {

var code = editor34474.getSession().getValue();

jQuery("#runBtn34474 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output34474").html("

"+data+"");
									jQuery(".maineditor34474 .code-editor-output").show();
									jQuery("#runBtn34474 i.run-code").hide();

} })

}

function closeoutput34474() { var code = editor34474.getSession().getValue(); jQuery(".maineditor34474 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn34474").addEventListener("click", copyCodeToClipboard34474); document.getElementById("runBtn34474").addEventListener("click", runCode34474); document.getElementById("closeoutputBtn34474").addEventListener("click", closeoutput34474);

Output:

Mastering Date and Time Retrieval in Python

Conclusion

In Python, obtaining the current time can be accomplished through various techniques such as ‘DateTime.now()’, the time() module, and ‘strftime()’. Each technique provides the versatility to present time in different formats, including UTC, GMT, and ISO. While `strftime()` is efficient for formatting time, gaining insights on these techniques can aid in retrieving the current time in Python.

The article Get Current Date and Time in Python was first published on Intellipaat Blog.

```


Leave a Reply

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

Share This