使用 Python,获取当前月份的第几天作为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4934783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:13:12  来源:igfitidea点击:

Using Python, get the day of the current month as an integer

pythondate

提问by ben55

I need to write a method that returns the day of the month as an integer. For example, if it's Feb 8th 2011, I want to have method like this:

我需要编写一个方法,将月份中的某天作为整数返回。例如,如果是 2011 年 2 月 8 日,我想要这样的方法:

>>> day = get_day_of_month()

where day would be given the integer value 8

其中 day 将被赋予整数值 8

采纳答案by programmersbook

>>> import datetime
>>> datetime.datetime.today().day

回答by diegueus9

from datetime import datetime

today = datetime.now()
today.day # this is a integer

回答by Tim

Or the "old school" (lower overhead, if it matters) method...

或者“老派”(较低的开销,如果重要的话)方法......

import time 
time.localtime(time.time())[2]

time.localtime() returns a tuple containing all of the elements of a timestamp.

time.localtime() 返回一个包含时间戳所有元素的元组。

回答by Acumenus

This is similar to the answer by programmersbook. It uses datetime.daterather than datetime.datetime.

这类似于程序员手册答案。它使用datetime.date而不是datetime.datetime.

>>> import datetime
>>> datetime.date.today().day
8