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 ...
随机推荐
- Openmp Runtime 库函数汇总(上)
Openmp Runtime 库函数汇总(上) omp_in_parallel,如果当前线程正在并行域内部,则此函数返回true,否则返回false. #include <stdio.h> ...
- 交叉编译esp8089
交叉编译esp8089 编译环境: 硬件:全志R528 ubuntu:Linux ubuntu 4.15.0-194-generic #205-Ubuntu SMP Fri Sep 16 19:49: ...
- Caddy-用Go写的新一代可扩展WebServer
前几天用 Netmaker 的时候发现它用 Caddy 替换掉了 Nginx,用了后发现确实简单好用,就安利一下. Caddy 是一个强大的.可扩展的平台,用 Go 编写,可以为你的站点.服务和应用程 ...
- java 进阶P-5.5+P-6.1
框架加数据 以框架+数据来提高可扩展性 命令的解析是否可以脱离if-else 定义一个Handler来处理命令 用Hash表来保存命令和Handler之间的关系 抽象 Shape是什么形状 Shape ...
- 静态static关键字概述-静态static关键字修饰成员变量
静态static关键字概述 概述 关于 static 关键字的使用,它可以用来修饰的成员变量和成员方法,被修饰的成员是属于类的,而不是单单是属 于某个对象的.也就是说,既然属于类,就可以不靠创建对象来 ...
- 行为型模式 - 观察者模式Observer
学习而来,代码是自己敲的.也有些自己的理解在里边,有问题希望大家指出. 有一个大佬视频中提过一个案例,我觉得很棒:遥闻深巷中犬吠,边有妇人惊觉欠伸,其夫呓语.继而儿醒,大啼.夫亦醒. 模式的定义与特点 ...
- 阿里百秀后台管理项目笔记 ---- Day03
来吧展示: step1:所有文章数据展示 引入 functions.php 文件执行数据库查询以及判断用户登录状态 require_once '../functions.php'; get_useri ...
- 第九周总结-MySQL、前端
多表查询的两种方式 1.连表操作: 1.1: inner join:内连接,将两张表共同的部分连接在一起生成一张新表.凭借顺序是把后面的表拼在前面表的后面,如果颠倒位置结果不同. select * f ...
- 登山(等级考试4级 测试卷 T1)
这道题目与 重启系统(等级考试4级 2021-03 T4)重启系统(等级考试4级 2021-03 T4) - 王浩泽 - 博客园 (cnblogs.com) 非常相似,于是乎呢就在这个程序上面改一改就 ...
- 【动画笔记】数据结构-AVL树的插入操作
本笔记前置知识: 二叉搜索(排序)树及其插入操作. 本文主要围绕AVL树的平衡因子.纸上做题思路.失衡类型(LL/RR/LR/RL).失衡调整方法.插入后回溯这几部分知识点展开. 注: 本笔记中的平衡 ...