Python - Everything about time, date
Time Module and current time
The most basic time-related module in Python is time.
import time now = time.time() print(type(now)) print(now)
The following is the result of running this Python code.
D:\tmp>python time_test.py <class 'float'> 1700043309.068374
The time.time() function returns a float type value.
This value is the elapsed time expressed in seconds based on 1970. This time is called UNIX time. Wikipedia explains UNIX time as follows:
Unix time[a] is a date and time representation widely used in computing. It measures time by the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970, the Unix epoch, without adjustments made due to leap seconds. In modern computing, values are sometimes stored with higher granularity, such as microseconds or nanoseconds.
UNIX time is the basis for time calculation in all programming languages.
Since the number 1700043309.068374 represents the elapsed time in seconds as of 00:00 on January 1, 1970, it is of course possible to display the current date and time (year, month, date, time) that is easy for us to understand from this value.
In general, time can be displayed in Greenwich Mean Time (GMT) standard time and the local time in the area where the user is located.
Based on GMT
The function that displays time based on GMT is time.gmtime(timestamp).
import time now = time.time() tm = time.gmtime(now) print(type(tm)) print("timestamp : ", tm) print("year : ", tm.tm_year) print("month : ", tm.tm_mon) print("day : ", tm.tm_mday) print("Hour : ", tm.tm_hour) print("Minute : ", tm.tm_min) print("Second : ", tm.tm_sec)
The following is the result of running this Python code.
DD:\tmp>python time_test.py <class 'time.struct_time'> timestamp : time.struct_time(tm_year=2023, tm_mon=11, tm_mday=15, tm_hour=10, tm_min=41, tm_sec=41, tm_wday=2, tm_yday=319, tm_isdst=0) year : 2023 month : 11 day : 15 Hour : 10 Minute : 41 Second : 41
You can see that the gmtime function changes the float type timestamp value into a structure that is easy for us to understand.
Based on LocalTime
To display local time, use the time.localtime(timestamp) function. This function reflects the difference in the gmtime value from the local time set on your computer. The data type of the variable returned by the localtime function is completely the same as that of the variable returned by gmtime.
import time now = time.time() tm = time.localtime(now) print(type(tm)) print("timestamp : ", tm) print("year : ", tm.tm_year) print("month : ", tm.tm_mon) print("day : ", tm.tm_mday) print("Hour : ", tm.tm_hour) print("Minute : ", tm.tm_min) print("Second : ", tm.tm_sec)
The following is the result of running this Python code.
DD:\tmp>python time_test.py <class 'time.struct_time'> timestamp : time.struct_time(tm_year=2023, tm_mon=11, tm_mday=15, tm_hour=10, tm_min=41, tm_sec=41, tm_wday=2, tm_yday=319, tm_isdst=0) year : 2023 month : 11 day : 15 Hour : 19 Minute : 41 Second : 41
The local time in my area (South Korea) is 9 hours different from GMT time.
Find elapsed time
To find the elapsed time, find the difference between the return values of the time.time() function.
import time from random import * start = time.time() # Do something here f = random() * 10 time.sleep(f) # random float between 0 and 1 end = time.time() print("Time Elapsed:{}".format(end - start))
The following is the result of running this Python code.
D:\tmp>python time_span.py Time Elapsed:2.3305420875549316
datetime Module
The time module uses elapsed time as of 00:00 on January 1, 1970. However, this module is not suitable for use as the year, month, and day standards that we often use in our daily lives. For example, if we want to find the date 30 days after February 1, we must check whether the year in question is a leap year. For example, if it is not a leap year, February should be counted as 27 days, and if it is a leap year, it should be counted as 28 days.
It is quite cumbersome for developers to do these calculations themselves. Python provides various modules to make these tasks easier.
Find the current time
Like the time module, the datetime module also provides a simple function now() to find the current time. The datetime.now() function returns the current local date and time. Please note that this is not GMT time.
from datetime import datetime now = datetime.now() print(type(now)) print("year : ", now.year) print("month : ", now.month) print("day : ", now.day) print("Hour : ", now.hour) print("Minute : ", now.minute) print("Second : ", now.second)print("microsecond : ", now.microsecond) print("Day of the week : ", now.weekday()) #Monday:0 Tuesday:1, ... print("string conversion : ", now.strftime('%Y-%m-%d %H:%M:%S'))
The following is the result of running this Python code.
D:\tmp>python time_test.py <class 'datetime.datetime'> year : 2023 month : 11 day : 15 Hour : 20 Minute : 9 Second : 24microsecond : 470013 Day of the week : 2 string conversion : 2023-11-15 20:12:40
The datetime module, unlike the time module, also supports days of the week, making it more useful.
timestamp to datetime and Vice Versa
Sometimes timestamp values need to be converted so that they can be used in the dateitme module.
import time from datetime import datetime tm = time.time() now = datetime.fromtimestamp(tm) print("year : ", now.year) print("month : ", now.month) print("day : ", now.day) print("Hour : ", now.hour) print("Minute : ", now.minute) print("Second : ", now.second) print("microsecond : ", now.microsecond) print("Day of the week : ", now.weekday()) #Monday:0 Tuesday:1, ... print("string conversion : ", now.strftime('%Y-%m-%d %H:%M:%S'))
<timestamp to datetime>
import time from datetime import datetime now = datetime.now() tm = time.mktime(now.timetuple()) print(type(tm)) print(tm)
<datetime to timestamp>
string date to datetime
Sometimes, it is necessary to convert the date value provided as a string so that it can be used in the dateitme module. Just use the datetime.strptime function.
import time from datetime import datetime date_str = "2021-12-31 17:05:00" now = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S') ''' This is also possible date_str = "20211231170500" now = datetime.strptime(date_str, '%Y%m%d%H%M%S') ''' print("year : ", now.year) print("month : ", now.month) print("day : ", now.day) print("Hour : ", now.hour) print("Minute : ", now.minute) print("Second : ", now.second) print("microsecond : ", now.microsecond) print("Day of the week : ", now.weekday()) #Monday:0 Tuesday:1, ... print("string conversion : ", now.strftime('%Y-%m-%d %H:%M:%S'))
Date after a certain amount of time (date)
This is a function that is often needed in reality. For example, if you want to know the date 150 days after November 10, 2023, do the following:
from datetime import datetime now = datetime.now() # After 1 hour one_hour_later = now + datetime.timedelta(hours=1) # Before 1 hour one_hour_ago = now - datetime.timedelta(hours=1) # 150 days after after_150d = now + datetime.timedelta(days=150) # 150 days before before_150d = now - datetime.timedelta(days=150) # After 10 minutes ten_minutes_later = now + datetime.timedelta(minutes=10) # before 10 minutes ten_minutes_later = now - datetime.timedelta(minutes=10)
Calculate date difference
The time difference between two dates is calculated as follows:
import time from datetime import datetime date1 = datetime.strptime("20231001000000", "%Y%m%d%H%M%S") date2 = datetime.strptime("20231225235959", "%Y%m%d%H%M%S") date_diff = date2 - date1 print("delta :", date_diff) print("days : ", date_diff.days) hours, remain = divmod(date_diff.seconds , 3600) #date_diff.seconds => remaining seconds minutes, seconds = divmod(remain , 60) print("Hours : ", hours) print("Minutes : ", minutes) print("Seconds : ", seconds)
The following is the result of running this Python code.
D:\tmp>python time_test.py delta : 85 days, 23:59:59 days : 85 Hours : 23 Minutes : 59 Seconds : 59
Wrapping up
I have previously written about handling time and dates in C/C++. If you are a C/C++ user, please refer to the following article.
댓글
댓글 쓰기