日期和时间在Python中

huangapple go评论65阅读模式
英文:

data and time in python

问题

import datetime

intDay = datetime.date(year=2023, month=4, day=4).weekday()
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print(days[intDay])

我希望星期和月份都打印在同一行上。

英文:

Code:

import datetime

intDay = datetime.date(year=2023, month=4, day=4).weekday()
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print(days[intDay])

I want both the week and the month to be printed on one line

答案1

得分: 1

import datetime

date = datetime.date(year=2023, month=4, day=4)
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

print("{} {}".format(date.strftime("%Y,%m,%d"), days[date.weekday()])) #2023,04,04 Tuesday

要更精确,您不需要为weekdays创建一个list,您可以直接使用strftime("%A")来获取星期几。

import datetime
date = datetime.date(year=2023, month=4, day=4)
print(date.strftime("%Y,%m,%d %A")) #2023,04,04 Tuesday
英文:

Code:

import datetime

date = datetime.date(year=2023, month=4, day=4)
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

print("{} {}".format(date.strftime("%Y,%m,%d"), days[date.weekday()])) #2023,04,04 Tuesday

To be more precise you don't need to create a list for weekdays you can directly obtained weekday using strftime("%A").

Code:

import datetime
date = datetime.date(year=2023, month=4, day=4)
print(date.strftime("%Y,%m,%d %A")) #2023,04,04 Tuesday

答案2

得分: 0

你可以使用strftime方法来获取你的输出。看看这段代码:

import datetime

date = datetime.date(year=2023, month=4, day=4)
intDay = date.weekday()
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
formatted_date = date.strftime("(%Y,%m,%d %A)")

print(formatted_date)

输出:

(2023,04,04 Tuesday)

英文:

You can use the strftime method to get your output. Look at this code:

 import datetime

 date = datetime.date(year=2023, month=4, day=4)
 intDay = date.weekday()
 days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
 formatted_date = date.strftime("(%Y,%m,%d %A)")

 print(formatted_date)

Output:

(2023,04,04 Tuesday)

huangapple
  • 本文由 发表于 2023年4月4日 16:58:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927403.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定