Bootstrap

python时间格式相互转化

一、时间戳转化时间

1、datetime

import time,datetime

a = 1655272800
date_stamp = datetime.datetime.fromtimestamp(a)
date_str = datetime.datetime.strftime(date_stamp ,"%Y-%m-%d %H:%M:%S")

2、time

import time
time_stamp= 1649755347
time_array = time.localtime(time_stamp)
checkpoint = time.strftime("%Y-%m-%d %H:%M:%S", time_array )

二、将其他字符串格式时间转化为自己需要的格式

1、datetime

import datetime
    
""" 2022/02/28 --> 2022-02-28 """
start_date = '2022/02/28'
middle = datetime.datetime.strptime('2022/02/28','%Y/%m/%d')
end_date = datetime.datetime.strftime(middle, "%Y-%m-%d")

2、time

import time 

""" 2022/02/28 --> 2022-02-28 """
start_date = '2022/02/28'
middle = time.strptime('2022/02/28','%Y/%m/%d')
end_date = time.strftime("%Y-%m-%d",middle)

3、获取月份的第一天和最后一天

import time,datetime
import calendar

# 获取月份的第一天和最后一天
def get_month_firstday_and_lastday(year=None, month=None):
    """
    :param year: 年份,默认是本年,可传int或str类型
    :param month: 月份,默认是本月,可传int或str类型
    :return: firstDay: 当月的第一天,datetime.date类型
              lastDay: 当月的最后一天,datetime.date类型
    """
    if year:
        year = int(year)
    else:
        year = datetime.date.today().year

    if month:
        month = int(month)
    else:
        month = datetime.date.today().month

    # 获取当月第一天的星期和当月的总天数
    firstDayWeekDay, monthRange = calendar.monthrange(year, month)

    # 获取当月的第一天
    firstDay = datetime.date(year=year, month=month, day=1)
    lastDay = datetime.date(year=year, month=month, day=monthRange)

    return firstDay, lastDay

;