python中周日历与时间的相互转换
python中周日历与时间的相互转换
基本介绍
在开发过程中,有些汇总咨询需要以周为单位统计,所以介绍下如何进行相互转换。
使用datetime类格式化进行转换
- strftime 方法可以将时间转换为字符串
- strptime 方法可以将字符串转为时间
- "%Y,%W,%w"中,"%Y"代表年份,"%W"代表周,"%w"代表一周内的第几天
from datetime import datetime
# 时间转周日历
a = datetime.now().strftime("%Y,%W,%w")
print(a) # 2022,28,3
# 周日历转时间
a = datetime.strptime("2022,12,3","%Y,%W,%w")
print(a) # 2022-03-23 00:00:00
问题
- 以上貌似问题解决了,但是问题出在年初和年尾
- 以2021年12月,2022年1月举例
2021年12月
| 周数 | 周一 | 周二 | 周三 | 周四 | 周五 | 周六 | 周日 |
|---|---|---|---|---|---|---|---|
| 48 | 1 | 2 | 3 | 4 | 5 | ||
| 49 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| 50 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| 51 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |
| 52 | 27 | 28 | 29 | 30 | 31 |
2022年1月
| 周数 | 周一 | 周二 | 周三 | 周四 | 周五 | 周六 | 周日 |
|---|---|---|---|---|---|---|---|
| 52 | 1 | 2 | |||||
| 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 2 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
| 3 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
| 4 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
| 5 | 31 |
from datetime import datetime
a = datetime.strptime("2021-12-31", "%Y-%m-%d")
print(a.strftime("%Y,%W,%w")) # 2021,52,5
a = datetime.strptime("2022-01-01", "%Y-%m-%d")
print(a.strftime("%Y,%W,%w")) # 2022,00,6
- 按iso标准,2022年1月1日应该归为2021年的最后一周
- 使用strftime方法格式化后为2022年第0月,所以这是有问题的
正确方法
使用isocalendar将日期转换为周日历
datetime类型的时间直接调用 isocalendar 方法
from datetime import datetime
def str_to_time(time_str: str) -> datetime:
return datetime.strptime(time_str, "%Y-%m-%d")
time_list = [
"2021-12-30",
"2021-12-31",
"2022-01-01",
"2022-01-02",
"2022-01-03",
]
for i in time_list:
t = str_to_time(i)
iso = t.isocalendar()
print(i, " > ", f"{iso.year},{iso.week},{iso.weekday}")
# 2021-12-30 > 2021,52,4
# 2021-12-31 > 2021,52,5
# 2022-01-01 > 2021,52,6
# 2022-01-02 > 2021,52,7
# 2022-01-03 > 2022,1,1
使用 fromisocalendar 将周日历转换为日期
from datetime import datetime
time_list = (
(2021, 52, 4),
(2021, 52, 5),
(2021, 52, 6),
(2021, 52, 7),
(2022, 1, 1),
)
for year, week, weekday in time_list:
t = datetime.fromisocalendar(year, week, weekday)
print(f"{year},{week},{weekday}", " > ", t)
# 2021,52,4 > 2021-12-30 00:00:00
# 2021,52,5 > 2021-12-31 00:00:00
# 2021,52,6 > 2022-01-01 00:00:00
# 2021,52,7 > 2022-01-02 00:00:00
# 2022,1,1 > 2022-01-03 00:00:00
python代码
from datetime import datetime
def datetime_to_isoweek(datetime_: datetime) -> tuple[int, int, int]:
"""时间转换为iso周日历
Args:
datetime_ (datetime): 时间
Returns:
tuple[int,int,int]: year,week,weekday
"""
iso = datetime_.isocalendar()
return iso.year, iso.week, iso.weekday
def isoweek_to_datetime(isoweek: tuple[int, int, int]) -> datetime:
"""iso周日历转换为时间
Args:
isoweek (tuple[int,int,int]): year,week,weekday
Returns:
datetime: 时间
"""
year, week, weekday = isoweek
return datetime.fromisocalendar(year, week, weekday)
python中周日历与时间的相互转换的更多相关文章
- Python中的日期和时间
感觉C语言作为一门编程的入门语言还是很好的,相比较之下,Python为代表的一些语言,适合很多非计算机专业的编程入门学习. Python 日期和时间 Python 程序能用很多方式处理日期和时间,转换 ...
- java/python中获取当前系统时间,并与字符串相互转换格式,或者转化成秒数,天数等整数
java转换成秒数 Date类有一个getTime()可以换回秒数,例如: public class DateToSecond { public static void main(String[] a ...
- python中字母与ascii码的相互转换
在做python编程时,碰到了需要将字母转换成ascii码的,原本以为用Int()就可以直接将字符串转换成整形了,可是int()带了一个默认参数,base=10,这里表示的是十进制,若出现字母,则会报 ...
- python中字符串与列表之间的相互转换
1.字符串>列表:split() a = 'my first python' b = a.split(" ") print(b)输出: 2.列表>字符串:join() ...
- python中 将字符串和字典的相互转换
1.首先引入json模块 # 引入json模块 import json 2.转换 #JSON到字典转化: dictinfo = json.loads(json_str) # 输出dict类型 字典到J ...
- python中时间的基本使用
格式化日期 我们可以使用 time 模块的 strftime 方法来格式化日期,: time.strftime(format[, t]) #!/usr/bin/python # -*- coding: ...
- Python中时间的处理之——timedelta篇
#! /usr/bin/python # coding=utf-8 from datetime import datetime,timedelta """ timed ...
- Python中日期和时间格式化输出的方法
本文转自:https://www.jb51.net/article/62518.htm 本文实例总结了python中日期和时间格式化输出的方法.分享给大家供大家参考.具体分析如下: python格式化 ...
- python中time()时间的相关问题
Python中time模块详解(转) 在平常的代码中,我们常常需要与时间打交道.在Python中,与时间处理有关的模块就包括:time,datetime以及calendar.这篇文章,主要讲解time ...
- 整理总结 python 中时间日期类数据处理与类型转换(含 pandas)
我自学 python 编程并付诸实战,迄今三个月. pandas可能是我最高频使用的库,基于它的易学.实用,我也非常建议朋友们去尝试它.--尤其当你本身不是程序员,但多少跟表格或数据打点交道时,pan ...
随机推荐
- 路由分发、名称空间、虚拟环境、视图层三板斧、JsonResponse对象、request对象获取文件、视图层FBV与CBV的源码剖析、模版层简介
今日内容详细 路由分发 django的每一个应用都可以有自己独立的路由层(urls.py)静态文件(static文件夹)模板层(templates文件夹) 基于这个特性多人开发项目就可以完全解 ...
- 使用小黄鸟(HttpCanary)+模拟器(VMOS Pro)对手机APP进行抓包
最近接触app开发,苦于app端不能像网页端可以F12看请求信息,对于后端来说当接口出现异常却不能拿到请求参数是很苦恼的, 因为之前了解过逍遥模拟器,先使用了模拟器对appj进行抓包,但发现这一款ap ...
- Codeforces Round #845 (Div. 2) and ByteRace 2023 A-D
Codeforces Round #845 (Div. 2) and ByteRace 2023 A-D A. Everybody Likes Good Arrays! 题意:对给定数组进行操作:删除 ...
- Flutter 3.7 正式发布
新的 Flutter 稳定版加入了 Material 3 更新.iOS 平台优化及其他内容 新年伊始,由 Flutter 3.7 正式版来「打头阵」!我们与整个 Flutter 社区成员们继续在 Fl ...
- VBA中的(升降序)排名问题
1 Sub 升序() 2 3 all_rows = Sheets(1).Range("a65536").End(xlUp).Row 4 5 With ActiveWorkbook. ...
- 主线程-创建Thread类的子类
主线程 Java使用java.lang.Thread类代表线程,所有的线程对象都必须是Thread类或其子类的实例.每个线程的作用是完成一定的任务,实际上就是执行一段程序流即一段顺序执行的代码.Jav ...
- 结构型模式 - 享元模式Flyweight
学习而来,代码是自己敲的.也有些自己的理解在里边,有问题希望大家指出. 更像是单例模式 + 简单工厂模式 享元模式的定义与特点 享元(Fiyweight)模式的定义:运用共享技术来有效的支持大量细粒度 ...
- 【分析笔记】Linux tasklet 机制的理解
Tasklet 介绍 Linux 内核提供的四种中断下半部中 softirq(软中断).tasklet(小任务).workqueue(工作队列) .request thread(中断线程)中的其中一种 ...
- 在windows系统下用vscode构造shell脚本IDE
1.基础环境搭建 安装Visual Studio Code(VScode ) 下载地址:https://code.visualstudio.com/Download 下载完双击文件,选择路径安装即可, ...
- 0x06_自制操作系统My-OS,IDT,GDT,PIC初始化,实现键盘中断
把class03改成class04 IDT,GDT,PIC 我来介绍什么是IDT和GDT,PIC,怎么实现键盘中断 GDT全局描述表在16位CPU用不到,到了32位CPU要用. 16位CPU实模式用基 ...