YouTip LogoYouTip

Python3 Date Time

# Python3 Date and Time ## Python3.x Python3 Date and Time Python programs can handle date and time in many ways. Converting date formats is a common functionality. Python provides the `time` and `calendar` modules to help format dates and times. Time intervals are floating-point numbers in seconds. Each timestamp represents the time elapsed since midnight (the epoch) of January 1, 1970. The Python `time` module provides 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 ```python #!/usr/bin/python3 import time # Import the time module ticks = time.time() print("Current timestamp:", ticks) The output of the above example: Current timestamp: 1459996086.7115328 Timestamps are best suited for date arithmetic. However, dates before 1970 cannot be represented this way. Dates too far in the future also cannot be used; UNIX and Windows only support up to 2038. * * * ## What is a Time Tuple? Many Python functions use a time tuple, which is a tuple of 9 numbers, to handle 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 calendar) | | 8 | Daylight savings | -1, 0, 1, -1 indicates the DST flag is unknown | This 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 | Whether it is Daylight Saving Time. Values: 1 (DST), 0 (not DST), -1 (unknown). Default is -1. | * * * ## Getting the Current Time To convert a timestamp (a floating-point number) to a time tuple, pass the floating-point number to a function like `localtime()`. ```python #!/usr/bin/python3 import time localtime = time.localtime(time.time()) print("Local time:", localtime) The output of the above example: Local time: 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 Formatted Time You can choose from various formats, but the simplest function to get a readable time string is `asctime()`: ```python #!/usr/bin/python3 import time localtime = time.asctime(time.localtime(time.time())) print("Local time:", localtime) The output of the above example: Local time: 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 ```python #!/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 a format string to a timestamp a = "Sat Mar 28 22:24:24 2016" print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y"))) The output of the above example: 2016-04-07 10:29:46 Thu Apr 07 10:29:46 2016 1459175064.0 Date and time format symbols in Python: * `%y` Two-digit year representation (00-99) * `%Y` Four-digit year representation (0000-9999) * `%m` Month (01-12) * `%d` Day of the month (0-31) * `%H` Hour (24-hour clock) (0-23) * `%I` Hour (12-hour clock) (01-12) * `%M` Minute (00-59) * `%S` Second (00-59) * `%a` Local abbreviated weekday name * `%A` Local full weekday name * `%b` Local abbreviated month name * `%B` Local full month name * `%c` Local appropriate date and time representation * `%j` Day of the year (001-366) * `%p` Local equivalent of AM or PM * `%U` Week number of the year (Sunday as the first day of the week) (00-53) * `%w` Weekday (0-6), Sunday is 0 * `%W` Week number of the year (Monday as the first day of the week) (00-53) * `%x` Local appropriate date representation * `%X` Local appropriate time representation * `%Z` Current time zone name * `%%` A literal '%' character * * * ## Getting a Month's Calendar The `calendar` module has wide methods to handle year and month calendars, for example, printing the calendar for a specific month: ## Example ```python #!/usr/bin/python3 import calendar cal = calendar.month(2016, 1) print("Here is the calendar for January 2016:") print(cal) The 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 * * * ## The Time Module The `time` module contains the following built-in functions, both for time handling and time format conversion: | Index | Function and Description | Example | | :--- | :--- | :--- | | 1 | `time.altzone` Returns the offset of the local (non-DST) timezone, west of UTC (negative in most of Western Europe, positive in the US, zero in the UK). Only available if DST is enabled. | The following example demonstrates the use of the `altzone()` function:
>>> import time
>>> print("time.altzone %d " % time.altzone)
time.altzone -28800 | | 2 | `time.asctime()` Accepts a time tuple and returns a readable 24-character string, such as "Tue Dec 11 18:07:14 2008". | The following example demonstrates the use of the `asctime()` function:
>>> import time
>>> t = time.localtime()
>>> print("time.asctime(t): %s " % time.asctime(t))
time.asctime(t): Thu Apr 7 10:36:20 2016 | | 3 | `time.clock()` Returns the current CPU time as a floating-point number in seconds. Useful for benchmarking different programs. More useful than `time.time()`. | (#)
This method is deprecated since Python 3.3 and removed in 3.8. Use the following two functions instead:
`time.perf_counter()` # Returns system running time
`time.process_time()` # Returns process running time | | 4 | `time.ctime()` Equivalent to `asctime(localtime(secs))`. Without arguments, equivalent to `asctime()`. | The following example demonstrates the use of the `ctime()` function:
>>> import time
>>> print("time.ctime() : %s" % time.ctime())
time.ctime() : Thu Apr 7 10:51:58 2016 | | 5 | `time.gmtime()` Accepts a timestamp (float seconds since the epoch) and returns a time tuple `t` in UTC. Note: `t.tm_isdst` is always 0. | The following example demonstrates the use of the `gmtime()` function:
>>> import time
>>> print("gmtime :", time.gmtime(1455508609.34375))
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()` Accepts a timestamp (float seconds since the epoch) and returns a time tuple `t` in local time. `t.tm_isdst` can be 0 or 1, depending on whether DST is in effect locally. | The following example demonstrates the use of the `localtime()` function:
>>> import time
>>> print("localtime(): ", time.localtime(1455508609.34375))
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)` Accepts a time tuple and returns a timestamp (float seconds since the epoch). | (#) | | 8 | `time.sleep(secs)` Suspends the calling thread for `secs` seconds. | The following example demonstrates the use of the `sleep()` function:
```python
#!/usr/bin/python3
import time
print("Start : %s" % time.ctime())
time.sleep(5)
print("End : %s" % time.ctime())
``` | | 9 | `time.strftime(fmt[, tupletime])` Accepts a time tuple and returns a readable string representing the local time, formatted according to `fmt`. | The following example demonstrates the use of the `strftime()` function:
>>> import time
>>> print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
2016-04-07 11:18:05 | | 10 | `time.strptime(str, fmt='%a %b %d %H:%M:%S %Y')` Parses a time string according to `fmt` and returns a time tuple. | The following example demonstrates the use of the `strptime()` function:
>>> import time
>>> struct_time = time.strptime("30 Nov 00", "%d %b %y")
>>> print("Returned tuple: ", struct_time)
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()` Returns the current timestamp (float seconds since the epoch). | The following example demonstrates the use of the `time()` function:
>>> import time
>>> print(time.time())
1459999336.1963577 | | 12 | `time.tzset()` Reinitializes the time-related settings based on the `TZ` environment variable. | (#) | | 13 | **`time.perf_counter()`** Returns the precise time of the timer (system running time), including the entire system's sleep time. Since the reference point of the return value is undefined, only the difference between consecutive calls is meaningful. | (#) | | 14 | **`time.process_time()`** Returns the sum of the CPU time used by the current process, excluding sleep time. Since the reference point of the return value is undefined, only the difference between consecutive calls is meaningful. | | The `time` module contains the following 2 very important attributes: | Index | Attribute and Description | | :--- | :--- | | 1 | **`time.timezone`** The attribute `time.timezone` is the offset in seconds of the local timezone (without DST) from UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa). | | 2 | **`time.tzname`** The attribute `time.tzname` is a pair of strings, the first is the name of the local timezone without DST, and the second is the name with DST. | * * * ## The Calendar Module The functions in this module are related to calendars, for example, printing the text calendar for a specific month. Monday is the default first day of the week, and Sunday is the default last day. To change this setting, use the `calendar.setfirstweekday()` function. The module contains the following built-in functions: | Index | Function and Description | | :--- | :--- | | 1 | **`calendar.calendar(year, w=2, l=1, c=6)`** Returns a multi-line string format calendar for the given `year`, with 3 months per line, separated by `c` spaces. The width of each day is `w` characters. The length of each line is `21*w + 18 + 2*c`. `l` is the number of lines for each week. | | 2 | **`calendar.firstweekday()`** Returns the current setting for the first day of the week. By default, when the `calendar` module is first loaded, it returns 0, which is Monday. | | 3 | **`calendar.isleap(year)`** Returns `True` if `year` is a leap year, otherwise `False`.
>>> import calendar
>>> print(calendar.isleap(2000))
True
>>> print(calendar.isleap(1900))
False | | 4 | **`calendar.leapdays(y1, y2)`** Returns the total number of leap years in the range `y1` to `y2` (inclusive). | | 5 | **`calendar.month(year, month, w=2, l=1)`** Returns a multi-line string format calendar for `year` and `month`, with a two-line header and one week per line. The width of each day is `w` characters. The length of each line is `7*w + 6`. `l` is the number of lines for each week. | | 6 | **`calendar.monthcalendar(year, month)`** Returns a single-layer nested list of integers. Each sublist represents a week. Days outside the month are set to 0; days within the month are represented by the day of the month, starting from 1. | | 7 | **`calendar.monthrange(year, month)`** Returns two integers. The first is the weekday of the first day of the month, and the second is the number of days in the month. The weekday is from 0 (Monday) to 6 (Sunday).
>>> import calendar
>>> calendar.monthrange(2014, 11)
(5, 30)
Explanation: 5 means the first day of November 2014 is Saturday, and 30 means November 2014 has 30 days. | | 8 | **`calendar.prcal(year, w=0, l=0, c=6, m=3)`** Equivalent to `print(calendar.calendar(year, w=0, l=0, c=6, m=3))`. | | 9 | **`calendar.prmonth(theyear, themonth, w=0, l=0)`** Equivalent to `print(calendar.month(theyear, themonth, w=0, l=0))`. | | 10 | **`calendar.setfirstweekday(weekday)`** Sets the first day of the week code. 0 (Monday) to 6 (Sunday). | | 11 | **`calendar.timegm(tupletime)`** The inverse of `time.gmtime()`: accepts a time tuple and returns the corresponding timestamp (float seconds since the epoch). | | 12 | **`calendar.weekday(year, month, day)`** Returns the weekday code for the given date. 0 (Monday) to 6 (Sunday). Month is 1 (January) to 12 (December). | * * * ## Other Related Modules and Functions In Python, other modules for handling dates and times include: * (https://docs.python.org/3/library/time.html) * (https://docs.python.org/3/library/datetime.html)
← Python3 Date TimePython3 Json β†’