1、字符串转时间datetime.strptime
import datetime
datetime.datetime.strptime('2020-08-1 ', "%Y-%m-%d")
datetime.datetime.strptime('2020-08-1 23:30:59', "%Y-%m-%d %H:%M:%S")
2、时间转字符串 datetime.strftime
import datetime
current_time = datetime.datetime.now() # 获取当前时间 datetime
datetime.datetime.strftime(current_time, "%Y-%m-%d %H:%M:%S")
注:对于UTC时间字符串,时间转换格式%Y-%m-%dT%H:%M:%SZ
import datetime
utc_time_string = "2021-08-01T12:34:56Z"
utc_datetime = datetime.datetime.strptime(utc_time_string, "%Y-%m-%dT%H:%M:%SZ")
3、获取datetime(时间类型)的某粒度时间(年/月/日/时/分/秒):
import datetime
current_time = datetime.datetime.now()
_year = current_time.year
_month = current_time.month
_day = current_time.day
_hour = current_time.hour
_minute = current_time.minute
_second = current_time.second
4、两个datetime的时间差(年/月/日/时/分/秒)
import datetime
# 给定日期字符串
date_str = '2023-10-17 01:05:16'
# 将日期字符串转换为 datetime 对象
given_date = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
# 获取今天的日期
current_time = datetime.datetime.now()
time_difference = current_time - given_date
# 相差秒数
time_difference.seconds
# 相差分钟数
time_difference.seconds/60
# 相差天数
time_difference.days
# 相差的月数
month_mun = (given_date.year - current_time.year)*12 + (given_date.month - current_time.month)
5、计算年龄(年为单位)
# 变量接上第4点
if current_time.month > given_date.month or (current_time.month == given_date.month and current_time.day > given_date.day):
age = current_time.year - given_date.year
else:
age = current_time.year - given_date.year - 1
标签:-%,python,datetime,current,time,date,格式,month
From: https://www.cnblogs.com/lanjianhua/p/18354918