Python3 Date and Time
Python programs can handle dates and times in various ways, and converting date formats is a common function.
Python provides a time and calendar module that can be used to format dates and times.
Time intervals are floating-point numbers in seconds.
Each timestamp is represented by the number of seconds that have elapsed since midnight of January 1, 1970 (epoch).
Python's time module has many functions to convert common date formats. For example, the function time.time() is used to get the current timestamp, as shown in the following example:
Example
#!/usr/bin/python3
import time # Import the time module
ticks = time.time()
print("Current timestamp is:", ticks)
Output of the above example:
Current timestamp is: 1459996086.7115328
Timestamp units are most suitable for date calculations. However, dates before 1970 cannot be represented this way. Very distant dates are also not supported, as UNIX and Windows only support up to the year 2038.
What is a Time Tuple?
Many Python functions use a tuple of 9 numbers to process time:
Index | Field | Value |
---|---|---|
0 | 4-digit year | 2008 |
1 | Month | 1 to 12 |
2 | Day | 1 to 31 |
3 | Hour | 0 to 23 |
4 | Minute | 0 to 59 |
5 | Second | 0 to 61 (60 or 61 are leap seconds) |
6 | Day of the week | 0 to 6 (0 is Monday) |
7 | Day of the year | 1 to 366 (Julian day) |
8 | Daylight saving time | -1, 0, 1, -1 is the flag to determine if it is daylight saving time |
The above is also known as the struct_time tuple. This structure has the following attributes:
Index | Attribute | Value |
---|---|---|
0 | tm_year | 2008 |
1 | tm_mon | 1 to 12 |
2 | tm_mday | 1 to 31 |
3 | tm_hour | 0 to 23 |
4 | tm_min | 0 to 59 |
5 | tm_sec | 0 to 61 (60 or 61 are leap seconds) |
6 | tm_wday | 0 to 6 (0 is Monday) |
7 | tm_yday | Day of the year, 1 to 366 |
8 | tm_isdst | Daylight saving time, values: 1(yes), 0(no), -1(unknown), default -1 |
Getting the Current Time
To convert from a timestamp represented as a floating-point number to a time tuple, simply pass the floating-point number to functions like localtime.
#!/usr/bin/python3
import time
localtime = time.localtime(time.time())
print("Local time is:", localtime)
Output of the above example:
Local time is: time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=28, tm_sec=49, tm_wday=3, tm_yday=98, tm_isdst=0)
Getting a Formatted Time
You can choose any format you need, but the simplest function to get a readable time pattern is asctime():
#!/usr/bin/python3
import time
localtime = time.asctime(time.localtime(time.time()))
print("Local time is:", localtime)
Output of the above example:
Local time is: Thu Apr 7 10:29:13 2016
Formatting Dates
We can use the strftime method of the time module to format dates:
time.strftime(format[, t])
Example
#!/usr/bin/python3
import time
# Format as 2016-03-20 11:45:39
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
# Format as Sat Mar 28 22:24:24 2016
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
# Convert the formatted string back to a timestamp
a = "Sat Mar 28 22:24:24 2016"
print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))
Output of the above example:
2016-03-20 11:45:39
Sat Mar 28 22:24:24 2016
1459192584.0
2016-04-07 10:29:46 Thu Apr 07 10:29:46 2016 1459175064.0
Python date and time formatting symbols:
- %y Two-digit year representation (00-99)
- %Y Four-digit year representation (0000-9999)
- %m Month (01-12)
- %d Day of the month (01-31)
- %H 24-hour format hour (00-23)
- %I 12-hour format hour (01-12)
- %M Minutes (00-59)
- %S Seconds (00-59)
- %a Abbreviated weekday name
- %A Full weekday name
- %b Abbreviated month name
- %B Full month name
- %c Local date and time representation
- %j Day of the year (001-366)
- %p Locale's equivalent of either AM or PM
- %U Week number of the year (00-53), with Sunday as the first day of the week
- %w Weekday as a decimal number (0-6), with Sunday as the first day of the week
- %W Week number of the year (00-53), with Monday as the first day of the week
- %x Local date representation
- %X Local time representation
- %Z Time zone name
- %% Percent sign itself
Get Calendar for a Month
The Calendar module has a wide range of methods to handle yearly and monthly calendars, such as printing a monthly calendar:
Example
#!/usr/bin/python3
import calendar
cal = calendar.month(2016, 1)
print("Here is the calendar for January 2016:")
print(cal)
Output of the above example:
Here is the calendar for January 2016:
January 2016
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Time Module
The Time module includes the following built-in functions, both for time processing and for converting time formats:
No. | Function and Description | Example |
---|---|---|
1 | time.altzone <br>Returns the offset in seconds from the Greenwich Mean Time for the region west of the Greenwich meridian, with negative values for regions east of the Greenwich meridian (such as Western Europe, including the UK). This is applicable only for regions that observe Daylight Saving Time. | Example usage of altzone() function: >>> import time<br>>>> print("time.altzone %d " % time.altzone)<br>time.altzone -28800 |
2 | time.asctime([tupletime]) <br>Accepts a time tuple and returns a readable 24-character string such as "Tue Dec 11 18:07:14 2008". | Example usage of asctime() function: >>> import time<br>>>> t = time.localtime()<br>>>> print("time.asctime(t): %s " % time.asctime(t))<br>time.asctime(t): Thu Apr 7 10:36:20 2016 |
3 | time.clock() <br>Deprecated since Python 3.3 and removed in Python 3.8. Use the following functions instead. time.perf_counter() # Returns the system runtime<br>time.process_time() # Returns the process runtime | |
4 | time.ctime([secs]) <br>Equivalent to asctime(localtime(secs)), and asctime() if no argument is provided. | Example usage of ctime() function: >>> import time<br>>>> print("time.ctime() : %s" % time.ctime())<br>time.ctime() : Thu Apr 7 10:51:58 2016 |
5 | time.gmtime([secs]) <br>Receives a timestamp (the number of seconds that have passed since the epoch 1970) and returns a time tuple t in Greenwich Mean Time. Note: t.tm_isdst is always 0. <br>The following example demonstrates the use of the gmtime() function: >>> import time<br>>>> print("gmtime :", time.gmtime(1455508609.34375))<br>gmtime : time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=3, tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst=0) | |
6 | time.localtime([secs]) <br>Receives a timestamp (the number of seconds that have passed since the epoch 1970) and returns a time tuple t in the local time (t.tm_isdst can be 0 or 1, depending on whether daylight saving time is in effect). <br>The following example demonstrates the use of the localtime() function: >>> import time<br>>>> print("localtime(): ", time.localtime(1455508609.34375))<br>localtime(): time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=11, tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst=0) | |
7 | time.mktime(tupletime) <br>Accepts a time tuple and returns a timestamp (the number of seconds that have passed since the epoch 1970). | Example |
8 | time.sleep(secs) <br>Delays the execution of the calling thread for the given number of seconds. <br>The following example demonstrates the use of the sleep() function: #!/usr/bin/python3<br>import time<br>print("Start : %s" % time.ctime())<br>time.sleep(5)<br>print("End : %s" % time.ctime()) | |
9 | time.strftime(fmt[,tupletime]) <br>Receives a time tuple and returns a readable string representing the local time, formatted according to fmt. <br>The following example demonstrates the use of the strftime() function: >>> import time<br>>>> print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))<br>2016-04-07 11:18:05 | |
10 | time.strptime(str,fmt='%a %b %d %H:%M:%S %Y') <br>Parses a time string into a time tuple according to the format specified by fmt. <br>The following example demonstrates the use of the strptime() function: >>> import time<br>>>> struct_time = time.strptime("30 Nov 00", "%d %b %y")<br>>>> print("Returned tuple: ", struct_time)<br>Returned tuple: time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1) | |
11 | time.time() <br>Returns the current timestamp (the number of seconds that have passed since the epoch 1970). <br>The following example demonstrates the use of the time() function: >>> import time<br>>>> print(time.time())<br>1459999336.1963577 | |
12 | time.tzset() <br>Reinitializes time-related settings according to the environment variable TZ. | Example |
13 | time.perf_counter() <br>Returns the precise time of the timer (system runtime), including the sleep time of the entire system. Since the reference point for the return value is undefined, only the difference between consecutive calls is valid. | Example |
14 | time.process_time() <br>Returns the sum of CPU time of the current process, excluding sleep time. Since the reference point for the return value is undefined, only the difference between consecutive calls is valid. |
The Time module includes the following two very important attributes:
No. | Attribute and Description |
---|---|
1 | time.timezone <br>The time.timezone attribute is the offset in seconds from Greenwich Mean Time (GMT) for the local time zone (not including daylight saving time) (greater than 0 in the Americas; less than or equal to 0 in most of Europe, Asia, Africa). |
2 | time.tzname <br>The time.tzname attribute includes a pair of strings that vary depending on the situation, one with the local time zone name including daylight saving time and one without. |
Calendar Module
The functions in this module are all related to calendars, such as printing a character calendar for a month.
Monday is the default first day of the week, and Sunday is the default last day. To change the setting, call the calendar.setfirstweekday() function. The module includes the following built-in functions:
No. | Function and Description |
---|---|
1 | calendar.calendar(year, w=2, l=1, c=6) <br>Returns a multi-line string format of the year calendar for the specified year, with 3 months per row and a spacing of c. Each day has a width of w characters. The length of each line is 21W+18+2C. l is the number of lines per week. |
2 | calendar.firstweekday() <br>Returns the current setting for the first day of the week. By default, it returns 0, which is Monday, when the calendar module is first loaded. |
3 | calendar.isleap(year) <br>Returns True if it is a leap year, otherwise False. >>> import calendar<br>>>> print(calendar.isleap(2000))<br>True<br>>>> print(calendar.isleap(1900))<br>False |
4 | calendar.leapdays(y1, y2) <br>Returns the total number of leap years between Y1 and Y2. |
5 | calendar.month(year, month, w=2, l=1) <br>Returns a multi-line string format of the calendar for the specified year and month, with two lines of headers and one line per week. Each day has a width of w characters. The length of each line is 7*W+6. l is the number of lines per week. |
6 | calendar.monthcalendar(year, month) <br>Returns a single-level nested list of integers. Each sublist contains integers representing a week. Dates outside the specified month and year are set to 0; dates within the range are represented by the day of the month starting from 1. |
7 | calendar.monthrange(year, month) <br>Returns two integers. The first is the day of the week for the first day of the month, and the second is the number of days in the month. The day of the week ranges from 0 (Monday) to 6 (Sunday). >>> import calendar<br>>>> calendar.monthrange(2014, 11)<br>(5, 30) Explanation: 5 indicates that the first day of November 2014 is a Saturday, and 30 indicates that November 2014 has 30 days. |
8 | calendar.prcal(year, w=0, l=0, c=6, m=3) <br>Equivalent to print(calendar.calendar(year, w=0, l=0, c=6, m=3)). |
9 | calendar.prmonth(theyear, themonth, w=0, l=0) <br>Equivalent to print(calendar.month(theyear, themonth, w=0, l=0)). |
10 | calendar.setfirstweekday(weekday) <br>Sets the starting day of the week code. From 0 (Monday) to 6 (Sunday). |
11 | calendar.timegm(tupletime) <br>The opposite of time.gmtime: accepts a time tuple and returns the timestamp (the number of floating-point seconds since the epoch of 1970). |
12 | calendar.weekday(year, month, day) <br>Returns the day code for the given date. From 0 (Monday) to 6 (Sunday). The month ranges from 1 (January) to 12 (December). |
Other Related Modules and Functions
In Python, other modules for handling dates and times include: