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 ...
随机推荐
- .Net 7 托管Main入口的四种类型
前言: 按照CLR的规则,C#托管Main入口其实有四种写法. 写法 第一种:最常见的,也是VS默认的,返回值void,带一个参数 static void Main(string[] args) { ...
- pycharm编辑器下载与使用
pycharm编辑器下载与使用 一.pycharm编辑器 1.pycharm编辑器 PyCharm是一种Python IDE,带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具.比如调 ...
- CSAPP 配套实验 DataLab
第一次写博客,当作随笔留给自己看吧,如果能帮到读者,是我的荣幸. 这是 CSAPP 的配套实验 DataLab,概括的来说就是在较严格的限制条件下把 15 个函数补充完整. 本人能力没有那么强,很多题 ...
- Java + SikuliX 基于图像实现自动化测试
转载请注明出处️ 作者:测试蔡坨坨 原文链接:caituotuo.top/6d2908e8.html 你好,我是测试蔡坨坨. 由于目前大多数GUI工具均需要依赖于程序类型进行特征属性识别,例如:Sel ...
- C++ 地球人口承载力
题目描述 假设地球上的新生资源按恒定速度增长.照此测算,地球上现有资源加上新生资源可供 xx 亿人生活 aa 年,或供 yy 亿人生活 bb 年. 为了能够实现可持续发展,避免资源枯竭,地球最多能够养 ...
- Linux07-常用命令-权限
1.组 1.1基本说明 在linux中的每个用户必须属于一个组,不能独立于组外.在linux中每个文件有所有者.所在组.其它组的概念. 1) 文件所有者 谁创建的这个文件,文件的所有者就是谁 2) 文 ...
- 聊聊火热的 ChatGPT(我帮大伙问了几个比较关心的问题)
如需要转载,请声明原文链接微信公众号「ENG八戒」https://mp.weixin.qq.com/s/L9tZy_KWnE1kf0E3HNhJhQ 本文大概 2562 个字,阅读需花 15 分钟 内 ...
- JDK、tomcat、MySQL5.7安装教程
JDK自定义安装 一.安装JDK.JRE 1.在E盘下建立一个java文件夹,在java文件夹下分别建立jdk和jre文件夹 2.双击安装包 3.点击下一步,更改安装路径,安装到第一步创建好的jdk文 ...
- SRS视频服务器CallBack的Demo
1.安装环境(很麻烦,可以选择编译启动) 官方文档快速开始docker配置: docker run --rm -it -p 1935:1935 -p 1985:1985 -p 8080:8080 -d ...
- C++练习3 定义带默认值的参数
通过void func 定义函数的默认值和其可以容纳多少个实参 1 #include <iostream> 2 using namespace std; 3 void func(int a ...