get函数获取指定时间的年、月、日等信息?
发布时间:2023-05-23 00:55:48
Python中的datetime模块提供了获取指定时间的年、月、日等信息的方法,主要有以下几种方式:
1.使用datetime.datetime.now获取当前时间
datetime.now()函数返回当前日期和时间,可以通过访问它的属性或方法来获取指定时间的年、月、日等信息。例如:
import datetime now = datetime.datetime.now() year = now.year month = now.month day = now.day hour = now.hour minute = now.minute second = now.second microsecond = now.microsecond print(year, month, day, hour, minute, second, microsecond)
2.使用datetime.datetime.strptime将字符串转换为datetime对象
如果需要获取指定日期的年、月、日等信息,就需要先将其转换为datetime对象,可以使用datetime.datetime.strptime函数将字符串转换为datetime对象。例如:
import datetime date_str = '2021-10-23' date = datetime.datetime.strptime(date_str, '%Y-%m-%d') year = date.year month = date.month day = date.day print(year, month, day)
3.使用datetime.date和datetime.time对象
我们也可以使用datetime.date和datetime.time对象分别获取日期和时间的信息。datetime.date对象包含year、month、day三个属性,而datetime.time对象包含hour、minute、second、microsecond四个属性。例如:
import datetime now = datetime.datetime.now() date = now.date() time = now.time() year = date.year month = date.month day = date.day hour = time.hour minute = time.minute second = time.second microsecond = time.microsecond print(year, month, day, hour, minute, second, microsecond)
4.使用time模块
除了datetime模块,Python还提供了time模块,其中的time.localtime函数返回当前时间的结构化时间(struct_time),我们可以通过访问其属性来获取对应的时间信息。例如:
import time current_time = time.localtime() year = current_time.tm_year month = current_time.tm_mon day = current_time.tm_mday hour = current_time.tm_hour minute = current_time.tm_min second = current_time.tm_sec print(year, month, day, hour, minute, second)
总结:以上四种方式均可获取指定时间的年、月、日等信息,具体选择哪种方式取决于实际情况,如字符串转换为datetime对象常用于读取csv文件中的日期数据,而time模块常用于与系统时间相关的操作。
