How to Get the System Date From Python
Python is a dynamic, interpreted programming language. Its features include a readable syntax, exception-based error handling, and an extensive library of modules, both official and published by third parties, for accomplishing common tasks. Like most common operations, retrieving the system date from Python is a simple task.
Instructions
-
-
1
Start python by typing the name "python" from the command line. Alternatively, you may have a Python development environment such as IDLE that you wish to use. If you prefer, start that instead.
-
2
Import the time module by typing the following code into the Python command prompt:
import time
-
-
3
Get the current time as a floating point number.
t = time.time()
This is technically the command that retrieves the system date. However, it is retrieved in a non-human readable form as the number of seconds that have elapsed since the 'epoch,' the point at which the computer considers time to have began. On Unix systems, this point is January first of 1970. Since human beings don't count time in terms of seconds since 1970, it is necessary to convert this value to a human readable format.
-
4
Print the time in a human readable format using the directive codes.
time.strftime('%X %x %Z')
The code %X prints out the time, using the format appropriate for the current locale of your system.
The code %x print out the date, using the format appropriate for your locale.
The code %Z prints out the time zone used by your system.
So, on one system, the following was returned by Python:
13:02:08 03/18/10 CDT
-
1
Tips & Warnings
Other codes you may want to try include:
%B The full name of the month.
%A The full name of the weekday.
%w The day of the week as a number between zero and six with Sunday as the first day.
%I The hour according to a twelve-hour clock.
There are a variety of others in the documentation for Python's time module, so you can precisely control how dates appear in your application.
The module cannot handle times before epoch time, such as pre-1970 in Unix, or times very distant in the future from epoch time, such as 2038 in Unix.
Generally, there is no need to delve into the details of epoch time in your applications, however it may be important to realize that its implementation differs within different operating systems.
References
- Photo Credit throw-over calendar image by Aleksandr Ugorenkov from Fotolia.com