Python 日期格式化,等日期相关操作

文章介绍了如何在Python中使用`time`和`datetime`模块进行时间格式化、时间戳转换以及计算特定时间差,如获取三天前的时间和UTC时间的构造。
摘要由CSDN通过智能技术生成

输入日期格式字符串 获取时间戳 构造时间,时间加减等

import time
import datetime

def format_time() -> None:
    """
日期格式化
    """
    inputStr1: str = input("输入一个时间格式的字符串")
    timeArray = time.strptime(inputStr1, '%Y-%m-%d %H:%M:%S')
    # 得到的是 float毫秒数
    intnumber = int(time.mktime(timeArray))

    timeArray = time.strptime(inputStr1, '%Y-%m-%d %H:%M:%S')
    str1 = time.strftime('%Y-%m-%d %H-%M-%S',timeArray)
    print(str1)


def three_days_age_time1() -> None:
    """
获取三天前时间
    """
    threeDaysAgoDateTime = datetime.datetime.now() - datetime.timedelta(days=3)
    timestamp1 = int(time.mktime(threeDaysAgoDateTime.timetuple()))

    # 格式直接转
    otherFormatStr = threeDaysAgoDateTime.strftime('%Y-%m-%d %H:%M:%S')
    print(otherFormatStr)

    # 时间戳构造
    dataArrary = datetime.datetime.utcfromtimestamp(timestamp1)
    print(dataArrary)


def timestamp_to_datetime() -> None:
    """
时间戳转日期字符串等
    """
    nowTime = int(time.time())
    structTime = time.localtime(nowTime)
    otherTime = time.strftime('%Y-%m-%d %H:%M:%S', structTime)
    print(otherTime)

    time.sleep(1)

    nowTime2 = datetime.datetime.now()
    str1 = nowTime2.strftime('%Y-%m-%d %H:%M:%S')
    print(str1)

    time.sleep(1)

    nowTime = time.localtime(1557502800)
    otherTime = time.strftime('%Y-%m-%d %H:%M:%S', nowTime)
    print(otherTime)

    dateArray = datetime.datetime.utcfromtimestamp(1557502900)
    datetimeFormatStr = dateArray.strftime('%Y-%m-%d %H:%M:%S')
    print(datetimeFormatStr)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值