python基础------时间戳、时间组、时间串、日期相互转化和日历以及练习

2023-11-07

1. 时间组、时间戳、时间串相互转化

import time
# 时间戳
tt=time.time()
print(tt)
# 时间组
b=time.localtime(tt)
print(b)
# 时间组转化为时间串(striftime,asctime)
c=time.strftime('%Y/%m/%d %H:%M:%S',b)
e=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
h=time.asctime(b)
print(c)
print(e)
print(h)
# 时间串转化为时间组
d=time.strptime('2019-01-01','%Y-%m-%d')
print(d)
# 时间戳转化为时间串(2种方法)
f=time.ctime(tt)
g=time.asctime(time.localtime(time.time()))
print(f)
print(g)

2. 时间组、日期、时间串之间相互转化

import time,datatime
# 时间串转化为时间组(stript)
a=time.strptime('2019-01-01 12:30:59','%Y-%m-%d %X')
print(a)
# 时间组转化为时间串(striftime,asctime)
b=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
c=time.asctime(time.localtime(time.time()))
print(b)
print(c)
#日期转化为时间组
d=datetime.datetime(2019,10,20)
datetime.timetuple()
#时间组转化为日期
e=time.localtime(time.time())
e1=datetime.datetime(e[0],e[1].e[2],e[3],e[4],e[5])
print(e1)
#日期转化为时间串
f=datetime.datetime(2019,10,20)
f1=datetime.strptime(f,'%Y-%m-%d')
print(f1)
#时间串转化为日期
g1='2019-2-18 8:30:20'
g=g1.strftime('%Y-%m-%d %H:%M:%S')
print(c)

3. 日历

import calendar
#打印2020年8月日历
calendar.prmonth(2020,8)
#以元组的形式返回,该月份第一天是星期几,以及月份的天数
print(calendar.monthrange(2021, 8))
#打印2019年日历
calendar.prcal(2019)
#打印2021年8月19日是星期几
print(calendar.weekday(2021, 8, 19)+1)
print(calendar.firstweekday())
calendar.setfirstweekday(1)
print(calendar.firstweekday())
#打印1980到2022年的闰年
for i in range(1980, 2022):
    if i%4==0:
        print(i,end=' ')
#判断2000到2022年闰年的数量
calendar.leapdays(2000,2022)
#判断是否是闰年
caleadar.isleap(2019)

案例一:

import time,calendar
atime=time.time()
print(atime)
# ②将atime时间戳转为转为本地时间组,保存在atuple中并打印输出
atuple=time.localtime(atime)
print(atuple)
# ③分别获取当前时间的年,月和日并打印输出
print(atuple[0])
print(atuple[1])
print(atuple[2])
# ④将atime时间戳转为UTC时间组,保存在gtuple中并打印输出
gtuple=time.gmtime(atime)
print(gtuple)
# ⑤将atuple时间组转为时间字符串,保存在astring中并打印输出
astring=time.strftime("%Y/%m/%d %H:%M:%S",gtuple)
print(astring)
# ⑥打印当前日期的月历
calendar.prmonth(2021,8)
# ⑦打印当前日期的年历
calendar.prcal(2021)
# ⑧打印当前
# 日期是星期几
print(calendar.weekday(2021, 8, 19)+1)
# (2)
# 时间操作:
# ①输入一个时间
t='2020-8-12 12:23:40'
# ②将该时间转为时间组
tt=time.strptime(t,"%Y-%m-%d %H:%M:%S")
print(tt)
# ③将时间组转为时间戳
ttt=time.mktime(tt)
print(ttt)

案例二:

# 提示用户输入日期,时间格式为2021 - 10 - 1
# d='2021-10-1'
# # 根据输入的字符串转化为相应的时间组并输出
d1=time.strptime(d,'%Y-%m-%d')
# # 将时间组再转化为相应的时间戳并输出
d2=time.mktime(d1)
print(d2)
# # 获取当前的时间戳
t=time.time()
print(t)
# # 计算距离国庆节还有多少天并且输出?
t1='2021/10/1'
t2=time.mktime(time.strptime(t1,'%Y/%m/%d'))
print('距离国庆剩余:{}天'.format((t2-t)/60/60/24))
# # 计算一下输入的日期是周几
a=input('请输入日期:')
b=time.strptime(a,'%Y/%m/%d')
print(b,type(b))
ayear=b[0]
amonth=b[1]
aday=b[2]
print(ayear)
c=calendar.weekday(ayear,amonth,aday)
print(f'{a}是星期{c+1}')
# 计算国庆节当天是周几?请重新输入密码
print(calendar.weekday(2021, 10, 1)+1)

案例三:

# 1)写出当前你电脑上的Unix时间(时间戳),输出内容以及它的类型
t=time.time()
print(t,type(t))
# 2)将它分别转化成本地时间组和格林尼治时间组并输出
print(time.localtime(time.time()))
print(time.gmtime(time.time()))
# 3)ylp =’2021 - 5 - 22 13: 07:00’是袁隆平院士去世的时间,请把这个字符串转换成时间组
ylp='2021-5-22 13:07:00'
ttp=time.strptime(ylp,'%Y-%m-%d %H:%M:%S')
print(ttp)
# 4)再把这个时间组转化为时间戳,并输出
ts=time.mktime(ttp)
print(ts)
# 5)计算并输出袁隆平院士去世的小时数,格式如下:
tp=time.time()
print('袁隆平去世小时数为:{}时'.format((tp-ts)/60/60))
# 4.写一个函数,随机生成三个数字y, m, d,分别作为年月日:
# 输出: 某某的生日是y年m月d日
import random,calendar
def birth():
    y=random.randint(1980,2021)
    m=random.randint(1,12)
    t=calendar.monthrange(y,m)
    d=random.randint(1,t[1])
    print(f'某某的生日是{y}{m}{d}日')

birth()

案例四:


# (1)读取数据信息
# ①使用文件处理方式,读取a.txt中的数据信息
# ②读取b.txt中的数据信息
import datetime
import calendar
import time
with open('a.txt','at+',encoding='utf8') as file:
    # file.write('2017/12/20')
    file.seek(0)
    a=file.read()
    print(a)
with open('b.txt','at+',encoding='utf8') as f:
    # f.write('2019/3/16')
    f.seek(0)
    b=f.read()
    print(b)
# (2)时间计算处理
# ①将两个文件中读取出的字符串信息转化为时间戳
# ②利用时间戳信息,比较两个时间相差多少天(时间戳信息差值,再将秒换算成天)
a1=datetime.datetime.strptime(a,'%Y/%m/%d')
a2=datetime.datetime.strptime(b,'%Y/%m/%d')
print(abs(a1-a2))
b1=time.mktime(time.strptime(a,'%Y/%m/%d'))
b2=time.mktime(time.strptime(b,'%Y/%m/%d'))
print(abs(b1-b2)/60/60/24)
# (3)查看自当天开始,向后20天所有周日的日期
# ①获取当天的日期
# ②使用循环,计算自当天推后1-20天的日期
# ③判断上一问中的日期是否是周日,满足条件就打印
a=datetime.datetime(2021,8,20)
for i in range(1,21):
    b=datetime.timedelta(days=i)
    c=a+b
    d=datetime.datetime(c.year,c.month,c.day)
    if d.isoweekday()==7:
        print(c)

案例五:


# ①使用datetime.date类获取当前日期并输出
# ②查找并输出从当前日期开始,30天前的日期
# ③查找并输出从当天开始到前30天之间所有周2对应的日期
# ④新建文件a.txt
# ⑤将所有周2的日期写入a.txt
print('----------------------------------------------')
d1=datetime.date.today()
aa=''
for i in range(1,30):
    b=datetime.timedelta(days=i)
    c = a + b
    if c.isoweekday()==2:
        aa+=str(c)+'\n'
        print(c)
with open('a1.txt','wt+') as file:
    file.write(aa)
    file.seek(0)
    b=file.read()
    print(b)

案例六:

#编写Python程序,将2015-1-16 12:00:00转化为unix时间,并计算此时间3天前的格式化时间和unix时间。
# ①获取当前主机信息:操作系统名
import sys,os,time,datetime,socket
print(os.name)
print(socket.gethostname())
# ②计算当前时间3天前的格式化时间和unix时间
print(time.strftime('%Y-%m-%d', time.localtime(time.time())))
print(time.time())
a=datetime.datetime.today()
b=datetime.timedelta(days=3)
print(a-b)
c=(a-b).strftime('%Y-%m-%d %H:%M:%S')
print(c)
d=time.mktime(time.strptime(c, '%Y-%m-%d %H:%M:%S'))
print(d)
# ③将获取到的当前时间写入文件 t1.txt 中,录屏演示时需要打开文件查看
with open('t1.txt','wt+') as file:
    file.write(str(time.time())+'\n')
    file.write(str(a-b)+'\n')
    file.write(str(c)+'\n')
    file.write(str(d))
    file.seek(0)
    b=file.read()
    print(b)
# 3.['吴文哲','刘鑫','冯鑫','杨欣冉','王欢']请在D盘的根目录下分别创建几个文件夹,分别以这几位同学的姓名命名。
# 请把创建的文件夹删除,并做到重复删除时不报错误。
print('---------------------------------------')
a=['吴文哲','刘鑫','冯鑫','杨欣冉','王欢']
for i in a:
    os.chdir(r'D:')
    os.mkdir(i)
    try:
        os.rmdir(i)
    except:
        print('重复删除')
# 4.在你的桌面上建文件夹目录如下:人工智能\1911A\jack
if not os.path.exists(r'C:\Users\86178\Desktop\人工智能\1911A\jack'):
    os.makedirs(r'C:\Users\86178\Desktop\人工智能\1911A\jack')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python基础------时间戳、时间组、时间串、日期相互转化和日历以及练习 的相关文章

随机推荐

  • Inno Setup入门

    一个最简单的安装脚本 1 最简单的安装文件脚本 setup AppName Test AppVerName TEST DefaultDirName E TEST AppVersion 1 0 files Source F desktop i
  • shell文件存在的判断 shell数组

    判断文件 WORKDIR home tmp LOCAL LIST FILE WORKDIR local list if no local txt file generate a new one if f LOCAL LIST FILE th
  • 解决QString类型中一些使用规则

    参考网页 http www kuqin com qtdocument qstring html fromLatin1 1 QString类型中的使用 QString str QString fromLatin1 123456789 5 st
  • nginx负载均衡与日志配置

    nginx负载均衡与日志配置 1 设置nginx负载均衡 1 1 找到nginx conf文件 并进行配置 2 设置nginx日志 2 1 找到nginx conf文件 配置日志nginx日志 2 查看 设置 1 设置nginx负载均衡 当
  • 史上无敌的超级详细的Node Js 环境搭建步骤

    今日分享内容 一 Node Js 环境搭建 1 Node js是什么 2 npm是什么 3 环境搭建步骤 二 Element简介 一 Node Js 环境搭建 1 Node js是什么 Node js是一个基于Chrome V8引擎的 Ja
  • DBCP 1.X 导致的生产环境部署问题

    应用部署到生产环境 启动后 首次登录没问题 再过几分钟或者说再次登录 却出现登录没响应 查询数据界面没响应等 数据库查询没响应的问题 但奇怪的是后台没任何不报错 初步怀疑是数据库会话数爆满引起的 通过LambdaProbe监控工具 发现应用
  • (入门题)题目 1579: 陶陶摘苹果2

    题目 陶陶家的院子里有一棵苹果树 每到秋天树上就会结出n个苹果 苹果成熟的时候 陶陶就会跑去摘苹果 陶陶有个30厘米高的板凳 当她不能直接用手摘到苹果的时候 就会踩到板凳上再试试 现在已知n个苹果到地面的高度 以及陶陶把手伸直的时候能够达到
  • 火影手游饰品分解

    文章目录 Part I 简介 Chap I 饰品种类与抗魔 Chap II 战力加成 Part II 强化消耗与分解返还 Chap I 祝福饰品分解返还与耗材 Chap II 祈愿饰品 130 Chap III 破晓饰品 140 及以后 P
  • 企业数字化转型过程中面临最大的挑战和问题是什么?

    无论组织规模如何 业务的敏捷性 弹性以及生产力的高低都是决定其发展运营成功与否的关键因素 而一个良好的数字化转型战略则是企业发展进步的有力助推器 麦肯锡称 借助数字化转型 可以实现 20 至 50 的经济收益和 20 至 30 的客户满意度
  • 【Unity】简单介绍使用Sprite Editor的四种裁剪

    学习目标 众所周知当我们在Untiy导入一张Sprite图的时候需要修改它的参数 如果精灵图中有多张图片 还要将其裁剪 今天简单介绍一下SpriteEditor中的三种模式 学习内容 首先我们要将一张图片模式设置成Mulitple模式 这样
  • leetcode 27 [remove val]

    leetcode 27 remove val 改进前 class Solution public int removeElement vector
  • 不做标题党软文营销如何写出好标题

    为软文选择出色的软文标题是任何内容营销策略不可或缺的一部分 吸引人的标题可以使读者点击开始阅读 知道什么标题效果好 这对软文的整体参与度和转化率有很大帮助 读者点开你的软文次数越多 业务就会获得更多的曝光度 因此引人注目的软文标题至关重要
  • 亲测——eclipse中windowBuilder插件的5种安装方式

    windowBuilder的安装方法 方法1 在Eclipse MarketPlace 插件市场中搜索在线安装 依次点击help Eclipse MarketPlace 在find中搜索 windowBuilder点击install安装即可
  • as3 java 交互_AS3与交互

    1 与Socket服务器建立连接 2 向Socket服务器发送数据 3 从Socket服务器读数据 4 同Socket服务器进行握手 并确定收到了什么样的数据和如何处理这些数据 5 与Socket服务器断开 或者当服务器想与你断开的时候发消
  • 漫步数理统计三十一——依分布收敛

    上篇博文我们介绍了依概率收敛的概念 利用着概念我们可以说统计量收敛到一个参数 而且在许多情况下即便不知道统计量的分布函数也能说明收敛 但是统计量有多接近估计量呢 本篇博文讲的收敛就回答了这个问题 定义1 textbf 23450 20041
  • 深圳地铁远期规划20条线路图首发

    深圳市城市轨道网络远期共规划了20条线路 总里程约748 5公里 含弹性发展线路约73 7公里 同时规划了5条城际线路 形成约146 2公里的城际线网 加上国家铁路 深圳市轨道交通总里程远景规划将达到1080公里 轨道规模和密度与东京等国际
  • git commit回退,lfs上传

    一 如何回退到之前的commit 1 查看之前的commit git log 选择一个commit 执行 git reset hard commit号 会清空当前目录下和仓库不一致的文件 回退commit但不删除代码 可以 git rese
  • 小程序调用接口报错,会返回 {“error“:600001,“errMsg“:“request:fail -102:net::ERR_CONNECTION_REFUSED“} 问题。

    error 600001 errMsg request fail 102 net ERR CONNECTION REFUSED 这个错误是网络连接被拒绝的错误 它通常表示无法建立与服务器的连接 这种问题可能有几个可能的原因 1 服务器故障
  • PyTorch 深度学习实践 第8讲

    第8讲 加载数据集 源代码 B站 刘二大人 传送门PyTorch深度学习实践 加载数据集 说明 1 DataSet 是抽象类 不能实例化对象 主要是用于构造我们的数据集 2 DataLoader 需要获取DataSet提供的索引 i 和le
  • python基础------时间戳、时间组、时间串、日期相互转化和日历以及练习

    1 时间组 时间戳 时间串相互转化 import time 时间戳 tt time time print tt 时间组 b time localtime tt print b 时间组转化为时间串 striftime asctime c ti