从一年中的某一天获取月份和该月的某一天

发布于 2025-01-18 09:27:00 字数 307 浏览 0 评论 0原文

我有这些数据”。 年、年中的某天,并且是闰年

需要根据给定数据打印“月、日”。

year= 2020
day_oy= 357

我试过了,

if day_ in range(1,32):
    new_month= "January"
elif day_ in range(32, 61):
    new_month= "February"

...

else:
    new_month= "December"

需要很多行。我需要用最少的线来完成它。

I have those data'.
Year, Day of the year and it's a Leap year

Need to print "Month, Day" from given data.

year= 2020
day_oy= 357

I tried,

if day_ in range(1,32):
    new_month= "January"
elif day_ in range(32, 61):
    new_month= "February"

...

else:
    new_month= "December"

and it takes many lines. And I need to do it using minimum lines.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

少女的英雄梦 2025-01-25 09:27:00
import datetime

day_of_the_year = 357
year = 2020

datetime_object = datetime.datetime(year, 1, 1) + datetime.timedelta(day_of_the_year - 1)

# get month and day of the month

month = datetime_object.month
day_of_the_month = datetime_object.day

print(f"{day_of_the_month}/{month}")

输出:

22/12

获得DateTime对象后,您可以以任何格式获取日期的任何详细信息。

有关更多详细信息,请参阅以下文档。

https://docs.python.org/3/library/library/datetime.htetime.htetime.html

import datetime

day_of_the_year = 357
year = 2020

datetime_object = datetime.datetime(year, 1, 1) + datetime.timedelta(day_of_the_year - 1)

# get month and day of the month

month = datetime_object.month
day_of_the_month = datetime_object.day

print(f"{day_of_the_month}/{month}")

Output:

22/12

Once you get the datetime object, you can get any details of the date in any format.

Refer to the below documentation for further details.

https://docs.python.org/3/library/datetime.html

梦里的微风 2025-01-25 09:27:00

基于此 q& a 您可能想要:

from datetime import datetime, timedelta

year = 2020
day_oy = 357

date = datetime(year=year, month=1, day=1)
date_oy = date + timedelta(days=day_oy - 1)
new_month = date_oy.strftime('%B')  # December

Based on this Q&A you probably want:

from datetime import datetime, timedelta

year = 2020
day_oy = 357

date = datetime(year=year, month=1, day=1)
date_oy = date + timedelta(days=day_oy - 1)
new_month = date_oy.strftime('%B')  # December
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文