python中周日历与时间的相互转换

周日历(ISO国际标准)介绍

在线周日历(2022年)

基本介绍

在开发过程中,有些汇总咨询需要以周为单位统计,所以介绍下如何进行相互转换。

使用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中周日历与时间的相互转换的更多相关文章

  1. Python中的日期和时间

    感觉C语言作为一门编程的入门语言还是很好的,相比较之下,Python为代表的一些语言,适合很多非计算机专业的编程入门学习. Python 日期和时间 Python 程序能用很多方式处理日期和时间,转换 ...

  2. java/python中获取当前系统时间,并与字符串相互转换格式,或者转化成秒数,天数等整数

    java转换成秒数 Date类有一个getTime()可以换回秒数,例如: public class DateToSecond { public static void main(String[] a ...

  3. python中字母与ascii码的相互转换

    在做python编程时,碰到了需要将字母转换成ascii码的,原本以为用Int()就可以直接将字符串转换成整形了,可是int()带了一个默认参数,base=10,这里表示的是十进制,若出现字母,则会报 ...

  4. python中字符串与列表之间的相互转换

    1.字符串>列表:split() a = 'my first python' b = a.split(" ") print(b)输出: 2.列表>字符串:join() ...

  5. python中 将字符串和字典的相互转换

    1.首先引入json模块 # 引入json模块 import json 2.转换 #JSON到字典转化: dictinfo = json.loads(json_str) # 输出dict类型 字典到J ...

  6. python中时间的基本使用

    格式化日期 我们可以使用 time 模块的 strftime 方法来格式化日期,: time.strftime(format[, t]) #!/usr/bin/python # -*- coding: ...

  7. Python中时间的处理之——timedelta篇

      #! /usr/bin/python # coding=utf-8 from datetime import datetime,timedelta """ timed ...

  8. Python中日期和时间格式化输出的方法

    本文转自:https://www.jb51.net/article/62518.htm 本文实例总结了python中日期和时间格式化输出的方法.分享给大家供大家参考.具体分析如下: python格式化 ...

  9. python中time()时间的相关问题

    Python中time模块详解(转) 在平常的代码中,我们常常需要与时间打交道.在Python中,与时间处理有关的模块就包括:time,datetime以及calendar.这篇文章,主要讲解time ...

  10. 整理总结 python 中时间日期类数据处理与类型转换(含 pandas)

    我自学 python 编程并付诸实战,迄今三个月. pandas可能是我最高频使用的库,基于它的易学.实用,我也非常建议朋友们去尝试它.--尤其当你本身不是程序员,但多少跟表格或数据打点交道时,pan ...

随机推荐

  1. Openmp Runtime 库函数汇总(上)

    Openmp Runtime 库函数汇总(上) omp_in_parallel,如果当前线程正在并行域内部,则此函数返回true,否则返回false. #include <stdio.h> ...

  2. Linux c 检测U盘挂载路径方法

    思路: 1.使用df -h |grep mnt shell 命令查找到挂载路径信息 本代码是将结果存入文件中,再从文件中解析出路径信息.也可使用fopen直接从管道中读取信息 2.解析出信息最后的/m ...

  3. (16)go-micro微服务jaeger链路追踪

    目录 一 jaeger链路追踪介绍 什么是链路追踪: 链路追踪主要功能: 二 jaeger链路追踪作用 三 jaeger链路追踪主要特性 四 jaeger链路追踪原理图 1.链路调用原理 2. 一次调 ...

  4. 鸿蒙系统应用开发之基于API6的蓝牙开发

    写在前面 由题意得,我今天讲的是基于鸿蒙系统的兼容JS的类Web开发范式的软件应用开发之蓝牙开发,它是基于API6的,至于为什么是基于API6,请你花几分钟看一下我之前写的这个系列教程的第四篇&quo ...

  5. MySQL优化六,锁

    一,MySQL中的锁 InnoDB中锁非常多,总的来说,可以如下分类: 这些锁都是做什么的?具体含义是什么?我们现在来一一学习. 1.2,解决并发事务问题 我们已经知道事务并发执行时可能带来的各种问题 ...

  6. 【分析笔记】全志方案通过命令行操作 GPIO 口(带源码分析)

    前言说明 在项目开发初期,很经常会需要临时操作某个GPIO来验证某些功能,可以通过编写一个简单的驱动程序来操作,但更方便的是可以通过命令行直接操作 GPIO ,这样不需要经过编写代码.编译驱动.推入文 ...

  7. vue3 | slots

    一.什么是插槽 插槽就是子组件中的提供给父组件使用的一个占位符,用<slot></slot>  表示,父组件可以在这个占位符中填充任何模板代码,如 HTML.组件等,填充的内容 ...

  8. 新版Bing 搜索后台的.NET 技术栈

    微软在今天在Redmond 线下举办媒体一场活动,发布了新版的微软必应,在桌面上推出了测试版,移动版也即将推出.微软首席执行官纳德拉称Al-powered搜索为公司自云15年以来最大的事情. 2023 ...

  9. maven打包失败 Cannot create resource output directory

    转https://blog.csdn.net/wuyuanshun/article/details/103097447 maven clean后打包出现Cannot create resource o ...

  10. 制作 2D 素材|基于 AI 5 天创建一个农场游戏,第 4 天

    欢迎使用 AI 进行游戏开发! 在本系列中,我们将使用 AI 工具在 5 天内创建一个功能完备的农场游戏.到本系列结束时,您将了解到如何将多种 AI 工具整合到游戏开发流程中.本系列文章将向您展示如何 ...