标签归档:date

如何验证python中的日期字符串格式?

问题:如何验证python中的日期字符串格式?

我有一个python方法,它接受日期输入作为字符串

如何添加验证以确保传递给方法的日期字符串在ffg中。格式:

'YYYY-MM-DD'

如果不是,则方法应该引发某种错误

I have a python method which accepts a date input as a string.

How do I add a validation to make sure the date string being passed to the method is in the ffg. format:

'YYYY-MM-DD'

if it’s not, method should raise some sort of error


回答 0

>>> import datetime
>>> def validate(date_text):
    try:
        datetime.datetime.strptime(date_text, '%Y-%m-%d')
    except ValueError:
        raise ValueError("Incorrect data format, should be YYYY-MM-DD")


>>> validate('2003-12-23')
>>> validate('2003-12-32')

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    validate('2003-12-32')
  File "<pyshell#18>", line 5, in validate
    raise ValueError("Incorrect data format, should be YYYY-MM-DD")
ValueError: Incorrect data format, should be YYYY-MM-DD
>>> import datetime
>>> def validate(date_text):
    try:
        datetime.datetime.strptime(date_text, '%Y-%m-%d')
    except ValueError:
        raise ValueError("Incorrect data format, should be YYYY-MM-DD")


>>> validate('2003-12-23')
>>> validate('2003-12-32')

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    validate('2003-12-32')
  File "<pyshell#18>", line 5, in validate
    raise ValueError("Incorrect data format, should be YYYY-MM-DD")
ValueError: Incorrect data format, should be YYYY-MM-DD

回答 1

Python的dateutil库是专门为这个(及以上)。它将自动datetime为您将其转换为对象,ValueError如果不能,则引发一个。

举个例子:

>>> from dateutil.parser import parse
>>> parse("2003-09-25")
datetime.datetime(2003, 9, 25, 0, 0)

ValueError如果日期格式不正确,则会引发一个:

>>> parse("2003-09-251")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 720, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 317, in parse
    ret = default.replace(**repl)
ValueError: day is out of range for month

dateutil如果将来开始需要解析其他格式,它也是非常有用的,因为它可以智能地处理大多数已知格式,并允许您修改规范:dateutil解析示例

如果需要,它还会处理时区。

基于注释的更新parse还接受关键字参数dayfirst,该参数控制在日期不明确的情况下预期日期是第一天还是第二个月。默认为False。例如

>>> parse('11/12/2001')
>>> datetime.datetime(2001, 11, 12, 0, 0) # Nov 12
>>> parse('11/12/2001', dayfirst=True)
>>> datetime.datetime(2001, 12, 11, 0, 0) # Dec 11

The Python dateutil library is designed for this (and more). It will automatically convert this to a datetime object for you and raise a ValueError if it can’t.

As an example:

>>> from dateutil.parser import parse
>>> parse("2003-09-25")
datetime.datetime(2003, 9, 25, 0, 0)

This raises a ValueError if the date is not formatted correctly:

>>> parse("2003-09-251")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 720, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 317, in parse
    ret = default.replace(**repl)
ValueError: day is out of range for month

dateutil is also extremely useful if you start needing to parse other formats in the future, as it can handle most known formats intelligently and allows you to modify your specification: dateutil parsing examples.

It also handles timezones if you need that.

Update based on comments: parse also accepts the keyword argument dayfirst which controls whether the day or month is expected to come first if a date is ambiguous. This defaults to False. E.g.

>>> parse('11/12/2001')
>>> datetime.datetime(2001, 11, 12, 0, 0) # Nov 12
>>> parse('11/12/2001', dayfirst=True)
>>> datetime.datetime(2001, 12, 11, 0, 0) # Dec 11

回答 2

我认为完整的验证功能应如下所示:

from datetime import datetime

def validate(date_text):
    try:
        if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
            raise ValueError
        return True
    except ValueError:
        return False

只执行

datetime.strptime(date_text, "%Y-%m-%d") 

这是不够的,因为strptime方法不检查该月和该月的哪一天是零填充的十进制数字。例如

datetime.strptime("2016-5-3", '%Y-%m-%d')

将被执行而没有错误。

I think the full validate function should look like this:

from datetime import datetime

def validate(date_text):
    try:
        if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
            raise ValueError
        return True
    except ValueError:
        return False

Executing just

datetime.strptime(date_text, "%Y-%m-%d") 

is not enough because strptime method doesn’t check that month and day of the month are zero-padded decimal numbers. For example

datetime.strptime("2016-5-3", '%Y-%m-%d')

will be executed without errors.


回答 3

from datetime import datetime

datetime.strptime(date_string, "%Y-%m-%d")

ValueError..如果收到不兼容的格式,则会引发a 。

..如果您要处理大量的日期和时间(就日期时间对象而言,而不是unix时间戳浮动),那么最好查看pytz模块,对于storage / db,将所有内容存储在UTC中。

from datetime import datetime

datetime.strptime(date_string, "%Y-%m-%d")

..this raises a ValueError if it receives an incompatible format.

..if you’re dealing with dates and times a lot (in the sense of datetime objects, as opposed to unix timestamp floats), it’s a good idea to look into the pytz module, and for storage/db, store everything in UTC.


回答 4

这是最简单的方法:

date = datetime.now()
date = date.strftime('%Y-%m-%d_%H-%M-%S.jpg')

This is the easiest way:

date = datetime.now()
date = date.strftime('%Y-%m-%d_%H-%M-%S.jpg')

如何使用python解析包含毫秒的时间字符串?

问题:如何使用python解析包含毫秒的时间字符串?

我能够用time.strptime解析包含日期/时间的字符串

>>> import time
>>> time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S')
(2009, 3, 30, 16, 31, 32, 0, 89, -1)

如何解析包含毫秒的时间字符串?

>>> time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/_strptime.py", line 333, in strptime
    data_string[found.end():])
ValueError: unconverted data remains: .123

I am able to parse strings containing date/time with time.strptime

>>> import time
>>> time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S')
(2009, 3, 30, 16, 31, 32, 0, 89, -1)

How can I parse a time string that contains milliseconds?

>>> time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/_strptime.py", line 333, in strptime
    data_string[found.end():])
ValueError: unconverted data remains: .123

回答 0

Python 2.6添加了一个新的strftime / strptime宏%f,该宏的执行时间为微秒。不知道这是否记录在任何地方。但是,如果您使用的是2.6或3.0,则可以执行以下操作:

time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')

编辑:我从来没有真正使用过该time模块,所以一开始我没有注意到这一点,但是看起来time.struct_time实际上并没有存储毫秒/微秒。最好使用datetime,例如:

>>> from datetime import datetime
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
>>> a.microsecond
123000

Python 2.6 added a new strftime/strptime macro %f, which does microseconds. Not sure if this is documented anywhere. But if you’re using 2.6 or 3.0, you can do this:

time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')

Edit: I never really work with the time module, so I didn’t notice this at first, but it appears that time.struct_time doesn’t actually store milliseconds/microseconds. You may be better off using datetime, like this:

>>> from datetime import datetime
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
>>> a.microsecond
123000

回答 1

我知道这是一个老问题,但是我仍在使用Python 2.4.3,我需要找到一种更好的方法将数据字符串转换为日期时间。

如果datetime不支持%f并且不需要try / except的解决方案是:

    (dt, mSecs) = row[5].strip().split(".") 
    dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6])
    mSeconds = datetime.timedelta(microseconds = int(mSecs))
    fullDateTime = dt + mSeconds 

这适用于输入字符串“ 2010-10-06 09:42:52.266000”

I know this is an older question but I’m still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.

The solution if datetime doesn’t support %f and without needing a try/except is:

    (dt, mSecs) = row[5].strip().split(".") 
    dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6])
    mSeconds = datetime.timedelta(microseconds = int(mSecs))
    fullDateTime = dt + mSeconds 

This works for the input string “2010-10-06 09:42:52.266000”


回答 2

要给出nstehr的答案所引用的代码(从其来源):

def timeparse(t, format):
    """Parse a time string that might contain fractions of a second.

    Fractional seconds are supported using a fragile, miserable hack.
    Given a time string like '02:03:04.234234' and a format string of
    '%H:%M:%S', time.strptime() will raise a ValueError with this
    message: 'unconverted data remains: .234234'.  If %S is in the
    format string and the ValueError matches as above, a datetime
    object will be created from the part that matches and the
    microseconds in the time string.
    """
    try:
        return datetime.datetime(*time.strptime(t, format)[0:6]).time()
    except ValueError, msg:
        if "%S" in format:
            msg = str(msg)
            mat = re.match(r"unconverted data remains:"
                           " \.([0-9]{1,6})$", msg)
            if mat is not None:
                # fractional seconds are present - this is the style
                # used by datetime's isoformat() method
                frac = "." + mat.group(1)
                t = t[:-len(frac)]
                t = datetime.datetime(*time.strptime(t, format)[0:6])
                microsecond = int(float(frac)*1e6)
                return t.replace(microsecond=microsecond)
            else:
                mat = re.match(r"unconverted data remains:"
                               " \,([0-9]{3,3})$", msg)
                if mat is not None:
                    # fractional seconds are present - this is the style
                    # used by the logging module
                    frac = "." + mat.group(1)
                    t = t[:-len(frac)]
                    t = datetime.datetime(*time.strptime(t, format)[0:6])
                    microsecond = int(float(frac)*1e6)
                    return t.replace(microsecond=microsecond)

        raise

To give the code that nstehr’s answer refers to (from its source):

def timeparse(t, format):
    """Parse a time string that might contain fractions of a second.

    Fractional seconds are supported using a fragile, miserable hack.
    Given a time string like '02:03:04.234234' and a format string of
    '%H:%M:%S', time.strptime() will raise a ValueError with this
    message: 'unconverted data remains: .234234'.  If %S is in the
    format string and the ValueError matches as above, a datetime
    object will be created from the part that matches and the
    microseconds in the time string.
    """
    try:
        return datetime.datetime(*time.strptime(t, format)[0:6]).time()
    except ValueError, msg:
        if "%S" in format:
            msg = str(msg)
            mat = re.match(r"unconverted data remains:"
                           " \.([0-9]{1,6})$", msg)
            if mat is not None:
                # fractional seconds are present - this is the style
                # used by datetime's isoformat() method
                frac = "." + mat.group(1)
                t = t[:-len(frac)]
                t = datetime.datetime(*time.strptime(t, format)[0:6])
                microsecond = int(float(frac)*1e6)
                return t.replace(microsecond=microsecond)
            else:
                mat = re.match(r"unconverted data remains:"
                               " \,([0-9]{3,3})$", msg)
                if mat is not None:
                    # fractional seconds are present - this is the style
                    # used by the logging module
                    frac = "." + mat.group(1)
                    t = t[:-len(frac)]
                    t = datetime.datetime(*time.strptime(t, format)[0:6])
                    microsecond = int(float(frac)*1e6)
                    return t.replace(microsecond=microsecond)

        raise

回答 3

上面的DNS答案实际上是不正确的。SO询问的时间是毫秒,但答案是毫秒。不幸的是,Python没有毫秒指令,只有毫秒(请参阅doc),但是您可以通过在字符串末尾附加三个零并将字符串解析为毫秒来解决该问题,例如:

datetime.strptime(time_str + '000', '%d/%m/%y %H:%M:%S.%f')

其中time_str的格式如下30/03/09 16:31:32.123

希望这可以帮助。

DNS answer above is actually incorrect. The SO is asking about milliseconds but the answer is for microseconds. Unfortunately, Python`s doesn’t have a directive for milliseconds, just microseconds (see doc), but you can workaround it by appending three zeros at the end of the string and parsing the string as microseconds, something like:

datetime.strptime(time_str + '000', '%d/%m/%y %H:%M:%S.%f')

where time_str is formatted like 30/03/09 16:31:32.123.

Hope this helps.


回答 4

我的第一个念头是尝试将其传递为“ 30/03/09 16:31:32.123”(在秒和毫秒之间使用句点而不是冒号)。但这没有用。快速浏览文档表明在任何情况下都将忽略小数秒…

啊,版本差异。据报道这是一个错误,现在在2.6+中,您可以使用“%S.%f”进行解析。

My first thought was to try passing it ’30/03/09 16:31:32.123′ (with a period instead of a colon between the seconds and the milliseconds.) But that didn’t work. A quick glance at the docs indicates that fractional seconds are ignored in any case…

Ah, version differences. This was reported as a bug and now in 2.6+ you can use “%S.%f” to parse it.


回答 5

从python邮件列表中:解析毫秒线程。尽管在作者的评论中提到,这有点像黑客,但其中张贴了一个似乎可以完成工作的功能。它使用正则表达式处理引发的异常,然后进行一些计算。

您还可以尝试先进行正则表达式和计算,然后再将其传递给strptime。

from python mailing lists: parsing millisecond thread. There is a function posted there that seems to get the job done, although as mentioned in the author’s comments it is kind of a hack. It uses regular expressions to handle the exception that gets raised, and then does some calculations.

You could also try do the regular expressions and calculations up front, before passing it to strptime.


回答 6

对于python 2我做到了

print ( time.strftime("%H:%M:%S", time.localtime(time.time())) + "." + str(time.time()).split(".",1)[1])

它打印时间“%H:%M:%S”,将time.time()拆分为两个子字符串(在。之前和之后。)xxxxxxx.xx,由于.xx是我的毫秒数,因此我将第二个子字符串添加到我的“% H:%M:%S“

希望有道理:)示例输出:

13:31:21.72闪烁01


13:31:21.81眨眼间01


13:31:26.3闪烁01


13:31:26.39眨眼间01


13:31:34.65起始车道01


For python 2 i did this

print ( time.strftime("%H:%M:%S", time.localtime(time.time())) + "." + str(time.time()).split(".",1)[1])

it prints time “%H:%M:%S” , splits the time.time() to two substrings (before and after the .) xxxxxxx.xx and since .xx are my milliseconds i add the second substring to my “%H:%M:%S”

hope that makes sense :) Example output:

13:31:21.72 Blink 01


13:31:21.81 END OF BLINK 01


13:31:26.3 Blink 01


13:31:26.39 END OF BLINK 01


13:31:34.65 Starting Lane 01



在Python中,如何将自纪元以来的秒数转换为`datetime`对象?

问题:在Python中,如何将自纪元以来的秒数转换为`datetime`对象?

所述time模块可使用秒因为历元进行初始化:

>>> import time
>>> t1=time.gmtime(1284286794)
>>> t1
time.struct_time(tm_year=2010, tm_mon=9, tm_mday=12, tm_hour=10, tm_min=19, 
                 tm_sec=54, tm_wday=6, tm_yday=255, tm_isdst=0)

有没有一种优雅的方法可以datetime.datetime以相同的方式初始化对象?

The time module can be initialized using seconds since epoch:

>>> import time
>>> t1=time.gmtime(1284286794)
>>> t1
time.struct_time(tm_year=2010, tm_mon=9, tm_mday=12, tm_hour=10, tm_min=19, 
                 tm_sec=54, tm_wday=6, tm_yday=255, tm_isdst=0)

Is there an elegant way to initialize a datetime.datetime object in the same way?


回答 0

datetime.datetime.fromtimestamp 如果您知道时区的话,您将产生与相同的输出 time.gmtime

>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)

要么

>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)

datetime.datetime.fromtimestamp will do, if you know the time zone, you could produce the same output as with time.gmtime

>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)

or

>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)

回答 1

纪元以来的秒数来datetimestrftime

>>> ts_epoch = 1362301382
>>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S')
>>> ts
'2013-03-03 01:03:02'

Seconds since epoch to datetime to strftime:

>>> ts_epoch = 1362301382
>>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S')
>>> ts
'2013-03-03 01:03:02'

回答 2

从文档中,从纪元以来的几秒钟内获取时区感知日期时间对象的推荐方法是:

Python 3

from datetime import datetime, timezone
datetime.fromtimestamp(timestamp, timezone.utc)

Python 2,使用pytz

from datetime import datetime
import pytz
datetime.fromtimestamp(timestamp, pytz.utc)

From the docs, the recommended way of getting a timezone aware datetime object from seconds since epoch is:

Python 3:

from datetime import datetime, timezone
datetime.fromtimestamp(timestamp, timezone.utc)

Python 2, using pytz:

from datetime import datetime
import pytz
datetime.fromtimestamp(timestamp, pytz.utc)

回答 3

请注意,datetime.datetime。fromtimestamp(时间戳)和。utcfromtimestamp(时间戳)在1970年1月1日之前的日期上在Windows上失败,而负的unix时间戳似乎在基于unix的平台上起作用。文档说:

如果时间戳不在平台C gmtime()函数支持的值范围内,则可能会引发ValueError。通常将其限制在1970年至2038年之间

另请参见Issue1646728

Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:

This may raise ValueError, if the timestamp is out of the range of values supported by the platform C gmtime() function. It’s common for this to be restricted to years in 1970 through 2038

See also Issue1646728


在python中格式化“昨天”的日期

问题:在python中格式化“昨天”的日期

我需要MMDDYY在Python中以这种格式找到“昨天”的日期。

例如,今天的日期将这样表示:111009

我今天可以轻松完成此操作,但是在“昨天”自动执行此操作有麻烦。

I need to find “yesterday’s” date in this format MMDDYY in Python.

So for instance, today’s date would be represented like this: 111009

I can easily do this for today but I have trouble doing it automatically for “yesterday”.


回答 0

datetime.timedelta()

>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'

Use datetime.timedelta()

>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'

回答 1

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')

回答 2

这应该做您想要的:

import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")

This should do what you want:

import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")

回答 3

所有答案都是正确的,但是我想提到时间增量接受否定论点

>>> from datetime import date, timedelta
>>> yesterday = date.today() + timedelta(days=-1)
>>> print(yesterday.strftime('%m%d%y')) #for python2 remove parentheses 

all answers are correct, but I want to mention that time delta accepts negative arguments.

>>> from datetime import date, timedelta
>>> yesterday = date.today() + timedelta(days=-1)
>>> print(yesterday.strftime('%m%d%y')) #for python2 remove parentheses 

回答 4

我可以将其设置为更具国际性,并根据国际标准设置日期格式,而不是在美国常见的怪异的月-日-年格式中吗?

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%Y-%m-%d')

Could I just make this somewhat more international and format the date according to the international standard and not in the weird month-day-year, that is common in the US?

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%Y-%m-%d')

回答 5

扩展克里斯给出的答案

如果您想以特定格式将日期存储在变量中,就我所知,这是最短,最有效的方法

>>> from datetime import date, timedelta                   
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'

如果您希望将其作为整数(可能会有用)

>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817

To expand on the answer given by Chris

if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know

>>> from datetime import date, timedelta                   
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'

If you want it as an integer (which can be useful)

>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817

从号码中获取月份名称

问题:从号码中获取月份名称

如何从月份编号中获得月份名称?

例如,如果我有3,我想返回march

date.tm_month()

如何获得字符串march

How can I get the month name from the month number?

For instance, if I have 3, I want to return march

date.tm_month()

How to get the string march?


回答 0

日历API

从中可以看到calendar.month_name[3]它将返回March,并且的数组索引0为空字符串,因此也无需担心零索引。

Calendar API

From that you can see that calendar.month_name[3] would return March, and the array index of 0 is the empty string, so there’s no need to worry about zero-indexing either.


回答 1

import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B")

返回:12月

有关Python文档网站的更多信息


[编辑:来自@GiriB的出色评论]您还可以使用%b它返回月份名称的缩写。

mydate.strftime("%b")

对于上面的示例,它将返回Dec

import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B")

Returns: December

Some more info on the Python doc website


[EDIT : great comment from @GiriB] You can also use %b which returns the short notation for month name.

mydate.strftime("%b")

For the example above, it would return Dec.


回答 2

import datetime

monthinteger = 4

month = datetime.date(1900, monthinteger, 1).strftime('%B')

print month

四月

import datetime

monthinteger = 4

month = datetime.date(1900, monthinteger, 1).strftime('%B')

print month

April


回答 3

如果您只需要知道给定数字(1-12)的月份名称,这就没有太大帮助,因为当前日期无关紧要。

calendar.month_name[i]

要么

calendar.month_abbr[i]

在这里更有用。

这是一个例子:

import calendar

for month_idx in range(1, 13):
    print (calendar.month_name[month_idx])
    print (calendar.month_abbr[month_idx])
    print ("")

样本输出:

January
Jan

February
Feb

March
Mar

...

This is not so helpful if you need to just know the month name for a given number (1 – 12), as the current day doesn’t matter.

calendar.month_name[i]

or

calendar.month_abbr[i]

are more useful here.

Here is an example:

import calendar

for month_idx in range(1, 13):
    print (calendar.month_name[month_idx])
    print (calendar.month_abbr[month_idx])
    print ("")

Sample output:

January
Jan

February
Feb

March
Mar

...

回答 4

import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B") # 'December'
mydate.strftime("%b") # 'dec'
import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B") # 'December'
mydate.strftime("%b") # 'dec'

回答 5

如果您(像我一样)在数据框中有一列月份数字,我将提供此信息:

df['monthName'] = df['monthNumer'].apply(lambda x: calendar.month_name[x])

I’ll offer this in case (like me) you have a column of month numbers in a dataframe:

df['monthName'] = df['monthNumer'].apply(lambda x: calendar.month_name[x])

回答 6

这就是我要做的:

from datetime import *

months = ["Unknown",
          "January",
          "Febuary",
          "March",
          "April",
          "May",
          "June",
          "July",
          "August",
          "September",
          "October",
          "November",
          "December"]

now = (datetime.now())
year = (now.year)
month = (months[now.month])
print(month)

输出:

>>> September

(这是我写这篇文章的真实日期)

This Is What I Would Do:

from datetime import *

months = ["Unknown",
          "January",
          "Febuary",
          "March",
          "April",
          "May",
          "June",
          "July",
          "August",
          "September",
          "October",
          "November",
          "December"]

now = (datetime.now())
year = (now.year)
month = (months[now.month])
print(month)

It Outputs:

>>> September

(This Was The Real Date When I Wrote This)


回答 7

一些好的 答案已经利用日历了,但是尚未提到设置语言环境的效果。

例如,法语:

import locale
import calendar

locale.setlocale(locale.LC_ALL, 'fr_FR')

assert calendar.month_name[1] == 'janvier'
assert calendar.month_abbr[1] == 'jan'

如果计划在setlocale代码中使用,请确保阅读文档中的提示和注意事项以及扩展编写器部分。此处显示的示例并不代表应如何使用它。特别是从这两部分中:

在某些库例程中调用setlocale()通常是一个坏主意,因为它的副作用是会影响整个程序[…]

扩展模块永远不要调用setlocale()[…]

Some good answers already make use of calendar but the effect of setting the locale hasn’t been mentioned yet.

Calendar set month names according to the current locale, for exemple in French:

import locale
import calendar

locale.setlocale(locale.LC_ALL, 'fr_FR')

assert calendar.month_name[1] == 'janvier'
assert calendar.month_abbr[1] == 'jan'

If you plan on using setlocale in your code, make sure to read the tips and caveats and extension writer sections from the documentation. The example shown here is not representative of how it should be used. In particular, from these two sections:

It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program […]

Extension modules should never call setlocale() […]


回答 8

对于arbitaray月度范围

month_integer=range(0,100)
map(lambda x: calendar.month_name[x%12+start],month_integer)

将产生正确的列表。start从一月在月份整数列表中开始的位置调整-parameter。

For arbitaray range of month numbers

month_integer=range(0,100)
map(lambda x: calendar.month_name[x%12+start],month_integer)

will yield correct list. Adjust start-parameter from where January begins in the month-integer list.


回答 9

8.1。datetime-基本日期和时间类型-Python 2.7.17文档 https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

所有strftime参数的列表。月份的名称以及诸如格式化之类的好东西,将零填满。阅读整页,了解诸如“天真的”参数规则之类的内容。这是简短的列表:%a周日,周一,…,星期六

%A周日,周一,…,周六

%w工作日为数字,其中0是星期日

%d每月的第一天02,…,31

%b 1月,2月,…,12月

%B一月,二月,…,十二月

%m月号,以零填充的01、02,…,12

%y 2位数字年份零填充00、01,…,99

%Y 4位数字1970、1988、2001、2013年

%H小时(24小时制),零填充00,01,…,23

%I小时(12小时制)零填充01,02,…,12

%p AM或PM。

%M分钟零填充00、01,…,59

%S第二个零填充00、01,…,59

%f微秒零填充000000,000001,…,999999

%z UTC偏移量,格式为+ HHMM或-HHMM + 0000,-0400,+ 1030

%Z时区名称UTC,EST,CST

%j一年中的当日零填充001、002,…,366

%U年份的周号零填充,第一个星期日之前的天是第0周

%W一年中的第几周(星期一作为第一天)

%c语言环境的日期和时间表示。1988年8月16日星期二21:30:00

%x语言环境的日期表示形式。1988年8月16日(zh_CN)

%X语言环境的时间表示形式。21:30:00

%%文字’%’字符。

8.1. datetime — Basic date and time types — Python 2.7.17 documentation https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

A list of all the strftime arguments. Names of months and nice stuff like formatting left zero fill. Read the full page for stuff like rules for “naive” arguments. Here is the list in brief: %a Sun, Mon, …, Sat

%A Sunday, Monday, …, Saturday

%w Weekday as number, where 0 is Sunday

%d Day of the month 01, 02, …, 31

%b Jan, Feb, …, Dec

%B January, February, …, December

%m Month number as a zero-padded 01, 02, …, 12

%y 2 digit year zero-padded 00, 01, …, 99

%Y 4 digit Year 1970, 1988, 2001, 2013

%H Hour (24-hour clock) zero-padded 00, 01, …, 23

%I Hour (12-hour clock) zero-padded 01, 02, …, 12

%p AM or PM.

%M Minute zero-padded 00, 01, …, 59

%S Second zero-padded 00, 01, …, 59

%f Microsecond zero-padded 000000, 000001, …, 999999

%z UTC offset in the form +HHMM or -HHMM +0000, -0400, +1030

%Z Time zone name UTC, EST, CST

%j Day of the year zero-padded 001, 002, …, 366

%U Week number of the year zero padded, Days before the first Sunday are week 0

%W Week number of the year (Monday as first day)

%c Locale’s date and time representation. Tue Aug 16 21:30:00 1988

%x Locale’s date representation. 08/16/1988 (en_US)

%X Locale’s time representation. 21:30:00

%% literal ‘%’ character.


回答 10

我创建了自己的函数,将数字转换为相应的月份。

def month_name (number):
    if number == 1:
        return "January"
    elif number == 2:
        return "February"
    elif number == 3:
        return "March"
    elif number == 4:
        return "April"
    elif number == 5:
        return "May"
    elif number == 6:
        return "June"
    elif number == 7:
        return "July"
    elif number == 8:
        return "August"
    elif number == 9:
        return "September"
    elif number == 10:
        return "October"
    elif number == 11:
        return "November"
    elif number == 12:
        return "December"

然后,我可以调用该函数。例如:

print (month_name (12))

输出:

>>> December

I created my own function converting numbers to their corresponding month.

def month_name (number):
    if number == 1:
        return "January"
    elif number == 2:
        return "February"
    elif number == 3:
        return "March"
    elif number == 4:
        return "April"
    elif number == 5:
        return "May"
    elif number == 6:
        return "June"
    elif number == 7:
        return "July"
    elif number == 8:
        return "August"
    elif number == 9:
        return "September"
    elif number == 10:
        return "October"
    elif number == 11:
        return "November"
    elif number == 12:
        return "December"

Then I can call the function. For example:

print (month_name (12))

Outputs:

>>> December

如何在Python中获取“时区感知”的datetime.today()值?

问题:如何在Python中获取“时区感知”的datetime.today()值?

我正在尝试从的值中减去一个日期值,datetime.today()以计算某物是多久以前的。但它抱怨:

TypeError: can't subtract offset-naive and offset-aware datetimes

该值datetime.today()似乎不是“时区感知”的,而我的其他日期值是。如何获得datetime.today()时区感知的值?

现在,这给了我当地时间,正好是PST,即UTC-8个小时。最坏的情况是,有没有一种方法可以手动将时区值输入datetime返回的对象datetime.today()并将其设置为UTC-8?

当然,理想的解决方案是让它自动知道时区。

I am trying to subtract one date value from the value of datetime.today() to calculate how long ago something was. But it complains:

TypeError: can't subtract offset-naive and offset-aware datetimes

The value datetime.today() doesn’t seem to be “timezone aware”, while my other date value is. How do I get a value of datetime.today() that is timezone aware?

Right now, it’s giving me the time in local time, which happens to be PST, i.e. UTC – 8 hours. Worst case, is there a way I can manually enter a timezone value into the datetime object returned by datetime.today() and set it to UTC-8?

Of course, the ideal solution would be for it to automatically know the timezone.


回答 0

在标准库中,没有跨平台的方法来创建感知时区而不创建自己的时区类。

在Windows上有win32timezone.utcnow(),但这是pywin32的一部分。我宁愿建议使用pytz库,该库具有大多数时区的不断更新的数据库。

使用本地时区可能非常棘手(请参见下面的“更多阅读”链接),因此您可能希望在整个应用程序中使用UTC,尤其是对于算术运算(如计算两个时间点之间的差)。

您可以像这样获取当前日期/时间:

import pytz
from datetime import datetime
datetime.utcnow().replace(tzinfo=pytz.utc)

记住这一点datetime.today()datetime.now()返回本地时间,而不是UTC时间,因此.replace(tzinfo=pytz.utc)向他们申请是不正确的。

另一个好的方法是:

datetime.now(pytz.utc)

这有点短,并且执行相同的操作。


进一步阅读/观看为什么在许多情况下更喜欢UTC:

In the standard library, there is no cross-platform way to create aware timezones without creating your own timezone class.

On Windows, there’s win32timezone.utcnow(), but that’s part of pywin32. I would rather suggest to use the pytz library, which has a constantly updated database of most timezones.

Working with local timezones can be very tricky (see “Further reading” links below), so you may rather want to use UTC throughout your application, especially for arithmetic operations like calculating the difference between two time points.

You can get the current date/time like so:

import pytz
from datetime import datetime
datetime.utcnow().replace(tzinfo=pytz.utc)

Mind that datetime.today() and datetime.now() return the local time, not the UTC time, so applying .replace(tzinfo=pytz.utc) to them would not be correct.

Another nice way to do it is:

datetime.now(pytz.utc)

which is a bit shorter and does the same.


Further reading/watching why to prefer UTC in many cases:


回答 1

获取特定时区的当前时间:

import datetime
import pytz
my_date = datetime.datetime.now(pytz.timezone('US/Pacific'))

Get the current time, in a specific timezone:

import datetime
import pytz
my_date = datetime.datetime.now(pytz.timezone('US/Pacific'))

回答 2

在Python 3中,标准库使将UTC指定为时区变得容易得多:

>>> import datetime
>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2016, 8, 26, 14, 34, 34, 74823, tzinfo=datetime.timezone.utc)

如果您想要一个仅使用标准库并且在Python 2和Python 3中均可使用的解决方案,请参见jfs的答案

如果您需要当地时区而不是UTC,请参见MihaiCapotă的答案

In Python 3, the standard library makes it much easier to specify UTC as the timezone:

>>> import datetime
>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2016, 8, 26, 14, 34, 34, 74823, tzinfo=datetime.timezone.utc)

If you want a solution that uses only the standard library and that works in both Python 2 and Python 3, see jfs’ answer.

If you need the local timezone, not UTC, see Mihai Capotă’s answer


回答 3

这是一个适用于Python 2和3的stdlib解决方案:

from datetime import datetime

now = datetime.now(utc) # Timezone-aware datetime.utcnow()
today = datetime(now.year, now.month, now.day, tzinfo=utc) # Midnight

其中today是一个已知的datetime实例,表示UTC中的一天的开始(午夜),并且utc是tzinfo对象(来自文档的示例):

from datetime import tzinfo, timedelta

ZERO = timedelta(0)

class UTC(tzinfo):
    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO

utc = UTC()

相关:在给定UTC时间获得午夜(一天的开始)几种方法的性能比较。注意:要获取具有非固定UTC偏移量的时区的午夜更为复杂。

Here’s a stdlib solution that works on both Python 2 and 3:

from datetime import datetime

now = datetime.now(utc) # Timezone-aware datetime.utcnow()
today = datetime(now.year, now.month, now.day, tzinfo=utc) # Midnight

where today is an aware datetime instance representing the beginning of the day (midnight) in UTC and utc is a tzinfo object (example from the documentation):

from datetime import tzinfo, timedelta

ZERO = timedelta(0)

class UTC(tzinfo):
    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO

utc = UTC()

Related: performance comparison of several ways to get midnight (start of a day) for a given UTC time. Note: it is more complex, to get midnight for a time zone with a non-fixed UTC offset.


回答 4

构造表示当前时间的时区感知日期时间对象的另一种方法:

import datetime
import pytz

pytz.utc.localize( datetime.datetime.utcnow() )  

Another method to construct time zone aware datetime object representing current time:

import datetime
import pytz

pytz.utc.localize( datetime.datetime.utcnow() )  

回答 5

从Python 3.3开始,仅使用标准库的单行代码就可以使用。您可以datetime使用来获取本地时区感知对象astimezone(如johnchen902建议):

from datetime import datetime, timezone

aware_local_now = datetime.now(timezone.utc).astimezone()

print(aware_local_now)
# 2020-03-03 09:51:38.570162+01:00

print(repr(aware_local_now))
# datetime.datetime(2020, 3, 3, 9, 51, 38, 570162, tzinfo=datetime.timezone(datetime.timedelta(0, 3600), 'CET'))

A one-liner using only the standard library works starting with Python 3.3. You can get a local timezone aware datetime object using astimezone (as suggested by johnchen902):

from datetime import datetime, timezone

aware_local_now = datetime.now(timezone.utc).astimezone()

print(aware_local_now)
# 2020-03-03 09:51:38.570162+01:00

print(repr(aware_local_now))
# datetime.datetime(2020, 3, 3, 9, 51, 38, 570162, tzinfo=datetime.timezone(datetime.timedelta(0, 3600), 'CET'))

回答 6

如果您使用的是Django,则可以将日期设置为非tz感知(仅UTC)。

在settings.py中注释以下行:

USE_TZ = True

If you are using Django, you can set dates non-tz aware (only UTC).

Comment the following line in settings.py:

USE_TZ = True

回答 7

pytz是一个Python库,可以使用Python 2.3或更高版本进行准确的跨平台时区计算。

使用stdlib,这是不可能的。

SO上看到类似的问题。

pytz is a Python library that allows accurate and cross platform timezone calculations using Python 2.3 or higher.

With the stdlib, this is not possible.

See a similar question on SO.


回答 8

这是使用stdlib生成它的一种方法:

import time
from datetime import datetime

FORMAT='%Y-%m-%dT%H:%M:%S%z'
date=datetime.strptime(time.strftime(FORMAT, time.localtime()),FORMAT)

date将存储本地日期和相对于UTC偏移量,而不是UTC时区的日期,因此,如果需要确定日期在哪个时区生成,可以使用此解决方案。在此示例中以及我的本地时区:

date
datetime.datetime(2017, 8, 1, 12, 15, 44, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))

date.tzname()
'UTC+02:00'

关键是将%z指令添加到表示形式FORMAT中,以指示生成的时间结构的UTC偏移量。其他表示形式可以在datetime模块文档中查询

如果您需要UTC时区的日期,则可以将time.localtime()替换为time.gmtime()

date=datetime.strptime(time.strftime(FORMAT, time.gmtime()),FORMAT)

date    
datetime.datetime(2017, 8, 1, 10, 23, 51, tzinfo=datetime.timezone.utc)

date.tzname()
'UTC'

编辑

这仅适用于python3。z指令在python 2 _strptime.py代码上不可用

Here is one way to generate it with the stdlib:

import time
from datetime import datetime

FORMAT='%Y-%m-%dT%H:%M:%S%z'
date=datetime.strptime(time.strftime(FORMAT, time.localtime()),FORMAT)

date will store the local date and the offset from UTC, not the date at UTC timezone, so you can use this solution if you need to identify which timezone the date is generated at. In this example and in my local timezone:

date
datetime.datetime(2017, 8, 1, 12, 15, 44, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))

date.tzname()
'UTC+02:00'

The key is adding the %z directive to the representation FORMAT, to indicate the UTC offset of the generated time struct. Other representation formats can be consulted in the datetime module docs

If you need the date at the UTC timezone, you can replace time.localtime() with time.gmtime()

date=datetime.strptime(time.strftime(FORMAT, time.gmtime()),FORMAT)

date    
datetime.datetime(2017, 8, 1, 10, 23, 51, tzinfo=datetime.timezone.utc)

date.tzname()
'UTC'

Edit

This works only on python3. The z directive is not available on python 2 _strptime.py code


回答 9

使用可识别时区的Python datetime.datetime.now()中所述的dateutil :

from dateutil.tz import tzlocal
# Get the current date/time with the timezone.
now = datetime.datetime.now(tzlocal())

Use dateutil as described in Python datetime.datetime.now() that is timezone aware:

from dateutil.tz import tzlocal
# Get the current date/time with the timezone.
now = datetime.datetime.now(tzlocal())

回答 10

在时区中获取可识别时区的日期utc足以使日期减法起作用。

但是,如果您想在当前时区使用时区感知日期,tzlocal则可以采用以下方法:

from tzlocal import get_localzone  # pip install tzlocal
from datetime import datetime
datetime.now(get_localzone())

PS dateutil具有类似的功能(dateutil.tz.tzlocal)。但是,尽管共享名称,但它具有完全不同的代码库,正如JF Sebastian 指出的那样,可能会产生错误的结果。

Getting a timezone-aware date in utc timezone is enough for date subtraction to work.

But if you want a timezone-aware date in your current time zone, tzlocal is the way to go:

from tzlocal import get_localzone  # pip install tzlocal
from datetime import datetime
datetime.now(get_localzone())

PS dateutil has a similar function (dateutil.tz.tzlocal). But inspite of sharing the name it has a completely different code base, which as noted by J.F. Sebastian can give wrong results.


回答 11

这是一个使用可读时区的解决方案,该解决方案适用于today():

from pytz import timezone

datetime.now(timezone('Europe/Berlin'))
datetime.now(timezone('Europe/Berlin')).today()

您可以列出所有时区,如下所示:

import pytz

pytz.all_timezones
pytz.common_timezones # or

Here is a solution using a readable timezone and that works with today():

from pytz import timezone

datetime.now(timezone('Europe/Berlin'))
datetime.now(timezone('Europe/Berlin')).today()

You can list all timezones as follows:

import pytz

pytz.all_timezones
pytz.common_timezones # or

回答 12

特别是对于非UTC时区:

唯一具有自己方法的时区是timezone.utc,但是如果需要,您可以使用timedeltatimezone,并使用强制使用UTC偏移量来伪装时区.replace

In [1]: from datetime import datetime, timezone, timedelta

In [2]: def force_timezone(dt, utc_offset=0):
   ...:     return dt.replace(tzinfo=timezone(timedelta(hours=utc_offset)))
   ...:

In [3]: dt = datetime(2011,8,15,8,15,12,0)

In [4]: str(dt)
Out[4]: '2011-08-15 08:15:12'

In [5]: str(force_timezone(dt, -8))
Out[5]: '2011-08-15 08:15:12-08:00'

在这里使用timezone(timedelta(hours=n))时区是真正的灵丹妙药,它还有许多其他有用的应用程序。

Especially for non-UTC timezones:

The only timezone that has its own method is timezone.utc, but you can fudge a timezone with any UTC offset if you need to by using timedelta & timezone, and forcing it using .replace.

In [1]: from datetime import datetime, timezone, timedelta

In [2]: def force_timezone(dt, utc_offset=0):
   ...:     return dt.replace(tzinfo=timezone(timedelta(hours=utc_offset)))
   ...:

In [3]: dt = datetime(2011,8,15,8,15,12,0)

In [4]: str(dt)
Out[4]: '2011-08-15 08:15:12'

In [5]: str(force_timezone(dt, -8))
Out[5]: '2011-08-15 08:15:12-08:00'

Using timezone(timedelta(hours=n)) as the time zone is the real silver bullet here, and it has lots of other useful applications.


回答 13

如果您在python中获得了当前时间和日期,则在导入日期和时间后,您将在python中获得当前日期和时间,如下所示。

from datetime import datetime
import pytz
import time
str(datetime.strftime(datetime.now(pytz.utc),"%Y-%m-%d %H:%M:%S%t"))

If you get current time and date in python then import date and time,pytz package in python after you will get current date and time like as..

from datetime import datetime
import pytz
import time
str(datetime.strftime(datetime.now(pytz.utc),"%Y-%m-%d %H:%M:%S%t"))

回答 14

在我看来,另一种替代方法是使用Pendulum代替pytz。考虑以下简单代码:

>>> import pendulum

>>> dt = pendulum.now().to_iso8601_string()
>>> print (dt)
2018-03-27T13:59:49+03:00
>>>

要安装Pendulum并查看其文档,请转到此处。它具有大量选项(例如简单的ISO8601,RFC3339和许多其他格式支持),更好的性能并倾向于产生更简单的代码。

Another alternative, in my mind a better one, is using Pendulum instead of pytz. Consider the following simple code:

>>> import pendulum

>>> dt = pendulum.now().to_iso8601_string()
>>> print (dt)
2018-03-27T13:59:49+03:00
>>>

To install Pendulum and see their documentation, go here. It have tons of options (like simple ISO8601, RFC3339 and many others format support), better performance and tend to yield simpler code.


回答 15

如下所示,将时区用于可识别时区的日期时间。默认为UTC:

from django.utils import timezone
today = timezone.now()

Use the timezone as shown below for a timezone-aware date time. The default is UTC:

from django.utils import timezone
today = timezone.now()

回答 16

来自“ howchoo”的Tyler撰写了一篇非常出色的文章,帮助我对Datetime Objects有了更好的了解,请点击以下链接

使用日期时间

本质上,我只是在两个datetime对象的末尾添加了以下内容

.replace(tzinfo=pytz.utc)

例:

import pytz
import datetime from datetime

date = datetime.now().replace(tzinfo=pytz.utc)

Tyler from ‘howchoo’ made a really great article that helped me get a better idea of the Datetime Objects, link below

Working with Datetime

essentially, I just added the following to the end of both my datetime objects

.replace(tzinfo=pytz.utc)

Example:

import pytz
import datetime from datetime

date = datetime.now().replace(tzinfo=pytz.utc)

回答 17

尝试pnp_datetime,所有使用和返回的时间都是带时区的,不会造成任何天真偏移和可感知偏移的问题。

>>> from pnp_datetime.pnp_datetime import Pnp_Datetime
>>>
>>> Pnp_Datetime.utcnow()
datetime.datetime(2020, 6, 5, 12, 26, 18, 958779, tzinfo=<UTC>)

try pnp_datetime, all the time been used and returned is with timezone, and will not cause any offset-naive and offset-aware issues.

>>> from pnp_datetime.pnp_datetime import Pnp_Datetime
>>>
>>> Pnp_Datetime.utcnow()
datetime.datetime(2020, 6, 5, 12, 26, 18, 958779, tzinfo=<UTC>)

回答 18

应该强调的是,从Python 3.6开始,您只需要标准的lib即可获取表示本地时间(操作系统的设置)的时区感知日期时间对象。使用astimezone()

import datetime

datetime.datetime(2010, 12, 25, 10, 59).astimezone()
# e.g.
# datetime.datetime(2010, 12, 25, 10, 59, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'Mitteleuropäische Zeit'))

datetime.datetime(2010, 12, 25, 12, 59).astimezone().isoformat()
# e.g.
# '2010-12-25T12:59:00+01:00'

# I'm on CET/CEST

(请参阅@ johnchen902的评论)。

It should be emphasized that since Python 3.6, you only need the standard lib to get a timezone aware datetime object that represents local time (the setting of your OS). Using astimezone()

import datetime

datetime.datetime(2010, 12, 25, 10, 59).astimezone()
# e.g.
# datetime.datetime(2010, 12, 25, 10, 59, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'Mitteleuropäische Zeit'))

datetime.datetime(2010, 12, 25, 12, 59).astimezone().isoformat()
# e.g.
# '2010-12-25T12:59:00+01:00'

# I'm on CET/CEST

(see @johnchen902’s comment). Note there’s a small caveat though, astimezone(None) gives aware datetime, unaware of DST.


在Python中创建日期范围

问题:在Python中创建日期范围

我想创建一个日期列表,从今天开始,然后返回任意天数,例如在我的示例中为100天。有没有比这更好的方法了?

import datetime

a = datetime.datetime.today()
numdays = 100
dateList = []
for x in range (0, numdays):
    dateList.append(a - datetime.timedelta(days = x))
print dateList

I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?

import datetime

a = datetime.datetime.today()
numdays = 100
dateList = []
for x in range (0, numdays):
    dateList.append(a - datetime.timedelta(days = x))
print dateList

回答 0

略胜一筹…

base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(numdays)]

Marginally better…

base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(numdays)]

回答 1

Pandas 一般而言,它非常适合时间序列,并且直接支持日期范围。

例如pd.date_range()

import pandas as pd
from datetime import datetime

datelist = pd.date_range(datetime.today(), periods=100).tolist()

它还具有许多使生活更轻松的选择。例如,如果您只想要工作日,则只需交换bdate_range

请参阅日期范围文档

此外,它完全支持pytz时区,并且可以平滑地跨越春季/秋季DST偏移。

OP编辑:

如果您需要实际的python日期时间,而不是Pandas时间戳:

import pandas as pd
from datetime import datetime

pd.date_range(end = datetime.today(), periods = 100).to_pydatetime().tolist()

#OR

pd.date_range(start="2018-09-09",end="2020-02-02")

这使用“ end”参数来匹配原始问题,但是如果您想降序使用日期:

pd.date_range(datetime.today(), periods=100).to_pydatetime().tolist()

Pandas is great for time series in general, and has direct support for date ranges.

For example pd.date_range():

import pandas as pd
from datetime import datetime

datelist = pd.date_range(datetime.today(), periods=100).tolist()

It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in bdate_range.

See date range documentation

In addition it fully supports pytz timezones and can smoothly span spring/autumn DST shifts.

EDIT by OP:

If you need actual python datetimes, as opposed to Pandas timestamps:

import pandas as pd
from datetime import datetime

pd.date_range(end = datetime.today(), periods = 100).to_pydatetime().tolist()

#OR

pd.date_range(start="2018-09-09",end="2020-02-02")

This uses the “end” parameter to match the original question, but if you want descending dates:

pd.date_range(datetime.today(), periods=100).to_pydatetime().tolist()

回答 2

获取指定开始日期和结束日期之间的日期范围(针对时间和空间复杂度进行了优化):

import datetime

start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y")
end = datetime.datetime.strptime("07-07-2014", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]

for date in date_generated:
    print date.strftime("%d-%m-%Y")

Get range of dates between specified start and end date (Optimized for time & space complexity):

import datetime

start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y")
end = datetime.datetime.strptime("07-07-2014", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]

for date in date_generated:
    print date.strftime("%d-%m-%Y")

回答 3

您可以编写一个生成器函数来返回从今天开始的日期对象:

import datetime

def date_generator():
  from_date = datetime.datetime.today()
  while True:
    yield from_date
    from_date = from_date - datetime.timedelta(days=1)

该生成器返回从今天开始的日期,并且一次返回一天。这是开始前三个日期的方法:

>>> import itertools
>>> dates = itertools.islice(date_generator(), 3)
>>> list(dates)
[datetime.datetime(2009, 6, 14, 19, 12, 21, 703890), datetime.datetime(2009, 6, 13, 19, 12, 21, 703890), datetime.datetime(2009, 6, 12, 19, 12, 21, 703890)]

与循环或列表理解相比,此方法的优势在于您可以返回任意多次。

编辑

使用生成器表达式而不是函数的更紧凑的版本:

date_generator = (datetime.datetime.today() - datetime.timedelta(days=i) for i in itertools.count())

用法:

>>> dates = itertools.islice(date_generator, 3)
>>> list(dates)
[datetime.datetime(2009, 6, 15, 1, 32, 37, 286765), datetime.datetime(2009, 6, 14, 1, 32, 37, 286836), datetime.datetime(2009, 6, 13, 1, 32, 37, 286859)]

You can write a generator function that returns date objects starting from today:

import datetime

def date_generator():
  from_date = datetime.datetime.today()
  while True:
    yield from_date
    from_date = from_date - datetime.timedelta(days=1)

This generator returns dates starting from today and going backwards one day at a time. Here is how to take the first 3 dates:

>>> import itertools
>>> dates = itertools.islice(date_generator(), 3)
>>> list(dates)
[datetime.datetime(2009, 6, 14, 19, 12, 21, 703890), datetime.datetime(2009, 6, 13, 19, 12, 21, 703890), datetime.datetime(2009, 6, 12, 19, 12, 21, 703890)]

The advantage of this approach over a loop or list comprehension is that you can go back as many times as you want.

Edit

A more compact version using a generator expression instead of a function:

date_generator = (datetime.datetime.today() - datetime.timedelta(days=i) for i in itertools.count())

Usage:

>>> dates = itertools.islice(date_generator, 3)
>>> list(dates)
[datetime.datetime(2009, 6, 15, 1, 32, 37, 286765), datetime.datetime(2009, 6, 14, 1, 32, 37, 286836), datetime.datetime(2009, 6, 13, 1, 32, 37, 286859)]

回答 4

是的,重新发明轮子…。只要在论坛上搜索,您将获得类似以下内容:

from dateutil import rrule
from datetime import datetime

list(rrule.rrule(rrule.DAILY,count=100,dtstart=datetime.now()))

yeah, reinvent the wheel…. just search the forum and you’ll get something like this:

from dateutil import rrule
from datetime import datetime

list(rrule.rrule(rrule.DAILY,count=100,dtstart=datetime.now()))

回答 5

您还可以使用日序使之更简单:

def date_range(start_date, end_date):
    for ordinal in range(start_date.toordinal(), end_date.toordinal()):
        yield datetime.date.fromordinal(ordinal)

或按照注释中的建议,您可以创建如下列表:

date_range = [
    datetime.date.fromordinal(ordinal) 
    for ordinal in range(
        start_date.toordinal(),
        end_date.toordinal(),
    )
]

You can also use the day ordinal to make it simpler:

def date_range(start_date, end_date):
    for ordinal in range(start_date.toordinal(), end_date.toordinal()):
        yield datetime.date.fromordinal(ordinal)

Or as suggested in the comments you can create a list like this:

date_range = [
    datetime.date.fromordinal(ordinal) 
    for ordinal in range(
        start_date.toordinal(),
        end_date.toordinal(),
    )
]

回答 6

我希望从该问题的标题中找到类似的内容range(),这样我就可以指定两个日期并创建一个包含所有日期的列表。这样,如果事先不知道这两个日期之间的天数,则无需计算。

因此,由于存在偏离主题的风险,因此此一线工作即可:

import datetime
start_date = datetime.date(2011, 01, 01)
end_date   = datetime.date(2014, 01, 01)

dates_2011_2013 = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))]

此答案的全部功劳!

From the title of this question I was expecting to find something like range(), that would let me specify two dates and create a list with all the dates in between. That way one does not need to calculate the number of days between those two dates, if one does not know it beforehand.

So with the risk of being slightly off-topic, this one-liner does the job:

import datetime
start_date = datetime.date(2011, 01, 01)
end_date   = datetime.date(2014, 01, 01)

dates_2011_2013 = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))]

All credits to this answer!


回答 7

这里有一个稍微不同的答案美国洛特的回答,让两个日期之间的日期列表的建设关startend。在下面的示例中,从2017年初到今天。

start = datetime.datetime(2017,1,1)
end = datetime.datetime.today()
daterange = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]

Here’s a slightly different answer building off of S.Lott’s answer that gives a list of dates between two dates start and end. In the example below, from the start of 2017 to today.

start = datetime.datetime(2017,1,1)
end = datetime.datetime.today()
daterange = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]

回答 8

我知道一个较晚的答案,但是我只是遇到了同样的问题,并决定在这方面缺少Python的内部范围函数,因此我在我的util模块中覆盖了它。

from __builtin__ import range as _range
from datetime import datetime, timedelta

def range(*args):
    if len(args) != 3:
        return _range(*args)
    start, stop, step = args
    if start < stop:
        cmp = lambda a, b: a < b
        inc = lambda a: a + step
    else:
        cmp = lambda a, b: a > b
        inc = lambda a: a - step
    output = [start]
    while cmp(start, stop):
        start = inc(start)
        output.append(start)

    return output

print range(datetime(2011, 5, 1), datetime(2011, 10, 1), timedelta(days=30))

A bit of a late answer I know, but I just had the same problem and decided that Python’s internal range function was a bit lacking in this respect so I’ve overridden it in a util module of mine.

from __builtin__ import range as _range
from datetime import datetime, timedelta

def range(*args):
    if len(args) != 3:
        return _range(*args)
    start, stop, step = args
    if start < stop:
        cmp = lambda a, b: a < b
        inc = lambda a: a + step
    else:
        cmp = lambda a, b: a > b
        inc = lambda a: a - step
    output = [start]
    while cmp(start, stop):
        start = inc(start)
        output.append(start)

    return output

print range(datetime(2011, 5, 1), datetime(2011, 10, 1), timedelta(days=30))

回答 9

根据我为自己写的答案:

import datetime;
print [(datetime.date.today() - datetime.timedelta(days=x)).strftime('%Y-%m-%d') for x in range(-5, 0)]

输出:

['2017-12-11', '2017-12-10', '2017-12-09', '2017-12-08', '2017-12-07']

区别在于我得到的是’ date‘对象,而不是’ datetime.datetime‘一个对象。

Based on answers I wrote for myself this:

import datetime;
print [(datetime.date.today() - datetime.timedelta(days=x)).strftime('%Y-%m-%d') for x in range(-5, 0)]

Output:

['2017-12-11', '2017-12-10', '2017-12-09', '2017-12-08', '2017-12-07']

The difference is that I get the ‘date‘ object, not the ‘datetime.datetime‘ one.


回答 10

如果有两个日期,并且您需要范围,请尝试

from dateutil import rrule, parser
date1 = '1995-01-01'
date2 = '1995-02-28'
datesx = list(rrule.rrule(rrule.DAILY, dtstart=parser.parse(date1), until=parser.parse(date2)))

If there are two dates and you need the range try

from dateutil import rrule, parser
date1 = '1995-01-01'
date2 = '1995-02-28'
datesx = list(rrule.rrule(rrule.DAILY, dtstart=parser.parse(date1), until=parser.parse(date2)))

回答 11

这是我根据自己的代码创建的要点,这可能会有所帮助。(我知道这个问题太旧了,但是其他人可以使用它)

https://gist.github.com/2287345

(下同)

import datetime
from time import mktime

def convert_date_to_datetime(date_object):
    date_tuple = date_object.timetuple()
    date_timestamp = mktime(date_tuple)
    return datetime.datetime.fromtimestamp(date_timestamp)

def date_range(how_many=7):
    for x in range(0, how_many):
        some_date = datetime.datetime.today() - datetime.timedelta(days=x)
        some_datetime = convert_date_to_datetime(some_date.date())
        yield some_datetime

def pick_two_dates(how_many=7):
    a = b = convert_date_to_datetime(datetime.datetime.now().date())
    for each_date in date_range(how_many):
        b = a
        a = each_date
        if a == b:
            continue
        yield b, a

Here is gist I created, from my own code, this might help. (I know the question is too old, but others can use it)

https://gist.github.com/2287345

(same thing below)

import datetime
from time import mktime

def convert_date_to_datetime(date_object):
    date_tuple = date_object.timetuple()
    date_timestamp = mktime(date_tuple)
    return datetime.datetime.fromtimestamp(date_timestamp)

def date_range(how_many=7):
    for x in range(0, how_many):
        some_date = datetime.datetime.today() - datetime.timedelta(days=x)
        some_datetime = convert_date_to_datetime(some_date.date())
        yield some_datetime

def pick_two_dates(how_many=7):
    a = b = convert_date_to_datetime(datetime.datetime.now().date())
    for each_date in date_range(how_many):
        b = a
        a = each_date
        if a == b:
            continue
        yield b, a

回答 12

这是一个供bash脚本获取工作日列表的衬板,它是python3。可以轻松地对其进行修改,最后的int是您想要的过去天数。

python -c "import sys,datetime; print('\n'.join([(datetime.datetime.today() - datetime.timedelta(days=x)).strftime(\"%Y/%m/%d\") for x in range(0,int(sys.argv[1])) if (datetime.datetime.today() - datetime.timedelta(days=x)).isoweekday()<6]))" 10

这是提供开始(或更确切地说,结束)日期的一种变体

python -c "import sys,datetime; print('\n'.join([(datetime.datetime.strptime(sys.argv[1],\"%Y/%m/%d\") - datetime.timedelta(days=x)).strftime(\"%Y/%m/%d \") for x in range(0,int(sys.argv[2])) if (datetime.datetime.today() - datetime.timedelta(days=x)).isoweekday()<6]))" 2015/12/30 10

这是任意开始日期和结束日期的变体。并不是说这不是非常有效,但是对于在bash脚本中放入for循环是有好处的:

python -c "import sys,datetime; print('\n'.join([(datetime.datetime.strptime(sys.argv[1],\"%Y/%m/%d\") + datetime.timedelta(days=x)).strftime(\"%Y/%m/%d\") for x in range(0,int((datetime.datetime.strptime(sys.argv[2], \"%Y/%m/%d\") - datetime.datetime.strptime(sys.argv[1], \"%Y/%m/%d\")).days)) if (datetime.datetime.strptime(sys.argv[1], \"%Y/%m/%d\") + datetime.timedelta(days=x)).isoweekday()<6]))" 2015/12/15 2015/12/30

Here’s a one liner for bash scripts to get a list of weekdays, this is python 3. Easily modified for whatever, the int at the end is the number of days in the past you want.

python -c "import sys,datetime; print('\n'.join([(datetime.datetime.today() - datetime.timedelta(days=x)).strftime(\"%Y/%m/%d\") for x in range(0,int(sys.argv[1])) if (datetime.datetime.today() - datetime.timedelta(days=x)).isoweekday()<6]))" 10

Here is a variant to provide a start (or rather, end) date

python -c "import sys,datetime; print('\n'.join([(datetime.datetime.strptime(sys.argv[1],\"%Y/%m/%d\") - datetime.timedelta(days=x)).strftime(\"%Y/%m/%d \") for x in range(0,int(sys.argv[2])) if (datetime.datetime.today() - datetime.timedelta(days=x)).isoweekday()<6]))" 2015/12/30 10

Here is a variant for arbitrary start and end dates. not that this isn’t terribly efficient, but is good for putting in a for loop in a bash script:

python -c "import sys,datetime; print('\n'.join([(datetime.datetime.strptime(sys.argv[1],\"%Y/%m/%d\") + datetime.timedelta(days=x)).strftime(\"%Y/%m/%d\") for x in range(0,int((datetime.datetime.strptime(sys.argv[2], \"%Y/%m/%d\") - datetime.datetime.strptime(sys.argv[1], \"%Y/%m/%d\")).days)) if (datetime.datetime.strptime(sys.argv[1], \"%Y/%m/%d\") + datetime.timedelta(days=x)).isoweekday()<6]))" 2015/12/15 2015/12/30

回答 13

Matplotlib相关

from matplotlib.dates import drange
import datetime

base = datetime.date.today()
end  = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
l = drange(base, end, delta)

Matplotlib related

from matplotlib.dates import drange
import datetime

base = datetime.date.today()
end  = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
l = drange(base, end, delta)

回答 14

我知道已经回答了,但是出于历史目的,我会给出答案,因为我认为这很简单。

import numpy as np
import datetime as dt
listOfDates=[date for date in np.arange(firstDate,lastDate,dt.timedelta(days=x))]

当然,它不会像代码高尔夫那样赢得胜利,但是我认为它很优雅。

I know this has been answered, but I’ll put down my answer for historical purposes, and since I think it is straight forward.

import numpy as np
import datetime as dt
listOfDates=[date for date in np.arange(firstDate,lastDate,dt.timedelta(days=x))]

Sure it won’t win anything like code-golf, but I think it is elegant.


回答 15

从Sandeep的答案开始,另一个向前或向后计数的示例。

from datetime import date, datetime, timedelta
from typing import Sequence
def range_of_dates(start_of_range: date, end_of_range: date) -> Sequence[date]:

    if start_of_range <= end_of_range:
        return [
            start_of_range + timedelta(days=x)
            for x in range(0, (end_of_range - start_of_range).days + 1)
        ]
    return [
        start_of_range - timedelta(days=x)
        for x in range(0, (start_of_range - end_of_range).days + 1)
    ]

start_of_range = datetime.today().date()
end_of_range = start_of_range + timedelta(days=3)
date_range = range_of_dates(start_of_range, end_of_range)
print(date_range)

[datetime.date(2019, 12, 20), datetime.date(2019, 12, 21), datetime.date(2019, 12, 22), datetime.date(2019, 12, 23)]

start_of_range = datetime.today().date()
end_of_range = start_of_range - timedelta(days=3)
date_range = range_of_dates(start_of_range, end_of_range)
print(date_range)

[datetime.date(2019, 12, 20), datetime.date(2019, 12, 19), datetime.date(2019, 12, 18), datetime.date(2019, 12, 17)]

请注意,开始日期包含在退货中,因此,如果您要总共四个日期,请使用 timedelta(days=3)

Another example that counts forwards or backwards, starting from Sandeep’s answer.

from datetime import date, datetime, timedelta
from typing import Sequence
def range_of_dates(start_of_range: date, end_of_range: date) -> Sequence[date]:

    if start_of_range <= end_of_range:
        return [
            start_of_range + timedelta(days=x)
            for x in range(0, (end_of_range - start_of_range).days + 1)
        ]
    return [
        start_of_range - timedelta(days=x)
        for x in range(0, (start_of_range - end_of_range).days + 1)
    ]

start_of_range = datetime.today().date()
end_of_range = start_of_range + timedelta(days=3)
date_range = range_of_dates(start_of_range, end_of_range)
print(date_range)

gives

[datetime.date(2019, 12, 20), datetime.date(2019, 12, 21), datetime.date(2019, 12, 22), datetime.date(2019, 12, 23)]

and

start_of_range = datetime.today().date()
end_of_range = start_of_range - timedelta(days=3)
date_range = range_of_dates(start_of_range, end_of_range)
print(date_range)

gives

[datetime.date(2019, 12, 20), datetime.date(2019, 12, 19), datetime.date(2019, 12, 18), datetime.date(2019, 12, 17)]

Note that the start date is included in the return, so if you want four total dates, use timedelta(days=3)


回答 16

from datetime import datetime, timedelta
from dateutil import parser
def getDateRange(begin, end):
    """  """
    beginDate = parser.parse(begin)
    endDate =  parser.parse(end)
    delta = endDate-beginDate
    numdays = delta.days + 1
    dayList = [datetime.strftime(beginDate + timedelta(days=x), '%Y%m%d') for x in range(0, numdays)]
    return dayList
from datetime import datetime, timedelta
from dateutil import parser
def getDateRange(begin, end):
    """  """
    beginDate = parser.parse(begin)
    endDate =  parser.parse(end)
    delta = endDate-beginDate
    numdays = delta.days + 1
    dayList = [datetime.strftime(beginDate + timedelta(days=x), '%Y%m%d') for x in range(0, numdays)]
    return dayList

回答 17

具有datetime和的每月日期范围生成器dateutil。简单易懂:

import datetime as dt
from dateutil.relativedelta import relativedelta

def month_range(start_date, n_months):
        for m in range(n_months):
            yield start_date + relativedelta(months=+m)

A monthly date range generator with datetime and dateutil. Simple and easy to understand:

import datetime as dt
from dateutil.relativedelta import relativedelta

def month_range(start_date, n_months):
        for m in range(n_months):
            yield start_date + relativedelta(months=+m)

回答 18

import datetime    
def date_generator():
    cur = base = datetime.date.today()
    end  = base + datetime.timedelta(days=100)
    delta = datetime.timedelta(days=1)
    while(end>base):
        base = base+delta
        print base

date_generator()
import datetime    
def date_generator():
    cur = base = datetime.date.today()
    end  = base + datetime.timedelta(days=100)
    delta = datetime.timedelta(days=1)
    while(end>base):
        base = base+delta
        print base

date_generator()

回答 19

从以上答案中,我为日期生成器创建了此示例

import datetime
date = datetime.datetime.now()
time = date.time()
def date_generator(date, delta):
  counter =0
  date = date - datetime.timedelta(days=delta)
  while counter <= delta:
    yield date
    date = date + datetime.timedelta(days=1)
    counter +=1

for date in date_generator(date, 30):
   if date.date() != datetime.datetime.now().date():
     start_date = datetime.datetime.combine(date, datetime.time())
     end_date = datetime.datetime.combine(date, datetime.time.max)
   else:
     start_date = datetime.datetime.combine(date, datetime.time())
     end_date = datetime.datetime.combine(date, time)
   print('start_date---->',start_date,'end_date---->',end_date)

From above answers i created this example for date generator

import datetime
date = datetime.datetime.now()
time = date.time()
def date_generator(date, delta):
  counter =0
  date = date - datetime.timedelta(days=delta)
  while counter <= delta:
    yield date
    date = date + datetime.timedelta(days=1)
    counter +=1

for date in date_generator(date, 30):
   if date.date() != datetime.datetime.now().date():
     start_date = datetime.datetime.combine(date, datetime.time())
     end_date = datetime.datetime.combine(date, datetime.time.max)
   else:
     start_date = datetime.datetime.combine(date, datetime.time())
     end_date = datetime.datetime.combine(date, time)
   print('start_date---->',start_date,'end_date---->',end_date)

在Python中为日期添加5天

问题:在Python中为日期添加5天

我有一个日期"10/10/11(m-d-y)",我想使用Python脚本为其添加5天。请考虑在月底也可以使用的一般解决方案。

我正在使用以下代码:

import re
from datetime import datetime

StartDate = "10/10/11"

Date = datetime.strptime(StartDate, "%m/%d/%y")

print Date ->正在打印 '2011-10-10 00:00:00'

现在,我想在此日期之前增加5天。我使用以下代码:

EndDate = Date.today()+timedelta(days=10)

哪个返回此错误:

name 'timedelta' is not defined

I have a date "10/10/11(m-d-y)" and I want to add 5 days to it using a Python script. Please consider a general solution that works on the month ends also.

I am using following code:

import re
from datetime import datetime

StartDate = "10/10/11"

Date = datetime.strptime(StartDate, "%m/%d/%y")

print Date -> is printing '2011-10-10 00:00:00'

Now I want to add 5 days to this date. I used the following code:

EndDate = Date.today()+timedelta(days=10)

Which returned this error:

name 'timedelta' is not defined

回答 0

先前的答案是正确的,但是通常这样做是更好的做法:

import datetime

然后,您将拥有datetime.timedelta

date_1 = datetime.datetime.strptime(start_date, "%m/%d/%y")

end_date = date_1 + datetime.timedelta(days=10)

The previous answers are correct but it’s generally a better practice to do:

import datetime

Then you’ll have, using datetime.timedelta:

date_1 = datetime.datetime.strptime(start_date, "%m/%d/%y")

end_date = date_1 + datetime.timedelta(days=10)

回答 1

导入timedeltadate首先。

from datetime import timedelta, date

date.today()会返回今天的日期时间,可能是您想要的

EndDate = date.today() + timedelta(days=10)

Import timedelta and date first.

from datetime import timedelta, date

And date.today() will return today’s datetime, may be you want

EndDate = date.today() + timedelta(days=10)

回答 2

如果您碰巧已经在使用pandas,则可以通过不指定格式来节省一些空间:

import pandas as pd
startdate = "10/10/2011"
enddate = pd.to_datetime(startdate) + pd.DateOffset(days=5)

If you happen to already be using pandas, you can save a little space by not specifying the format:

import pandas as pd
startdate = "10/10/2011"
enddate = pd.to_datetime(startdate) + pd.DateOffset(days=5)

回答 3

我想您缺少这样的东西:

from datetime import timedelta

I guess you are missing something like that:

from datetime import timedelta

回答 4

这是另一种使用dateutil的relativedelta添加日期的方法。

from datetime import datetime
from dateutil.relativedelta import relativedelta

print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S') 
date_after_month = datetime.now()+ relativedelta(days=5)
print 'After 5 Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')

输出:

今天:25/06/2015 15:56:09

5天后:30/06/2015 15:56:09

Here is another method to add days on date using dateutil’s relativedelta.

from datetime import datetime
from dateutil.relativedelta import relativedelta

print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S') 
date_after_month = datetime.now()+ relativedelta(days=5)
print 'After 5 Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')

Output:

Today: 25/06/2015 15:56:09

After 5 Days: 30/06/2015 15:56:09


回答 5

如果要立即添加日期,可以使用此代码

from datetime import datetime
from datetime import timedelta


date_now_more_5_days = (datetime.now() + timedelta(days=5) ).strftime('%Y-%m-%d')

If you want add days to date now, you can use this code

from datetime import datetime
from datetime import timedelta


date_now_more_5_days = (datetime.now() + timedelta(days=5) ).strftime('%Y-%m-%d')

回答 6

这是从现在开始+指定天数的功能

import datetime

def get_date(dateFormat="%d-%m-%Y", addDays=0):

    timeNow = datetime.datetime.now()
    if (addDays!=0):
        anotherTime = timeNow + datetime.timedelta(days=addDays)
    else:
        anotherTime = timeNow

    return anotherTime.strftime(dateFormat)

用法:

addDays = 3 #days
output_format = '%d-%m-%Y'
output = get_date(output_format, addDays)
print output

Here is a function of getting from now + specified days

import datetime

def get_date(dateFormat="%d-%m-%Y", addDays=0):

    timeNow = datetime.datetime.now()
    if (addDays!=0):
        anotherTime = timeNow + datetime.timedelta(days=addDays)
    else:
        anotherTime = timeNow

    return anotherTime.strftime(dateFormat)

Usage:

addDays = 3 #days
output_format = '%d-%m-%Y'
output = get_date(output_format, addDays)
print output

回答 7

为了减少冗长的代码,并避免datetime和datetime.datetime之间的名称冲突 ,应使用CamelCase名称重命名这些类。

from datetime import datetime as DateTime, timedelta as TimeDelta

因此,您可以执行以下操作,我认为这更清楚。

date_1 = DateTime.today() 
end_date = date_1 + TimeDelta(days=10)

另外,如果您以后想要的话,也不会出现名称冲突import datetime

In order to have have a less verbose code, and avoid name conflicts between datetime and datetime.datetime, you should rename the classes with CamelCase names.

from datetime import datetime as DateTime, timedelta as TimeDelta

So you can do the following, which I think it is clearer.

date_1 = DateTime.today() 
end_date = date_1 + TimeDelta(days=10)

Also, there would be no name conflict if you want to import datetime later on.


回答 8

使用timedeltas可以做到:

import datetime
today=datetime.date.today()


time=datetime.time()
print("today :",today)

# One day different .
five_day=datetime.timedelta(days=5)
print("one day :",five_day)
#output - 1 day , 00:00:00


# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)


# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)
#output - 
today : 2019-05-29
one day : 5 days, 0:00:00
fitfthday 2019-06-03

using timedeltas you can do:

import datetime
today=datetime.date.today()


time=datetime.time()
print("today :",today)

# One day different .
five_day=datetime.timedelta(days=5)
print("one day :",five_day)
#output - 1 day , 00:00:00


# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)


# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)
#output - 
today : 2019-05-29
one day : 5 days, 0:00:00
fitfthday 2019-06-03

回答 9

通常,您现在没有答案,但是也许我创建的我的类也会有所帮助。对我来说,它可以解决我在Pyhon项目中曾经遇到的所有要求。

class GetDate:
    def __init__(self, date, format="%Y-%m-%d"):
        self.tz = pytz.timezone("Europe/Warsaw")

        if isinstance(date, str):
            date = datetime.strptime(date, format)

        self.date = date.astimezone(self.tz)

    def time_delta_days(self, days):
        return self.date + timedelta(days=days)

    def time_delta_hours(self, hours):
        return self.date + timedelta(hours=hours)

    def time_delta_seconds(self, seconds):
        return self.date + timedelta(seconds=seconds)

    def get_minimum_time(self):
        return datetime.combine(self.date, time.min).astimezone(self.tz)

    def get_maximum_time(self):
        return datetime.combine(self.date, time.max).astimezone(self.tz)

    def get_month_first_day(self):
        return datetime(self.date.year, self.date.month, 1).astimezone(self.tz)

    def current(self):
        return self.date

    def get_month_last_day(self):
        lastDay = calendar.monthrange(self.date.year, self.date.month)[1]
        date = datetime(self.date.year, self.date.month, lastDay)
        return datetime.combine(date, time.max).astimezone(self.tz)

如何使用它

  1. self.tz = pytz.timezone("Europe/Warsaw") -在此处定义要在项目中使用的时区
  2. GetDate("2019-08-08").current()-这会将您的字符串日期转换为具有您在pt 1中定义的时区的时间敏感对象。默认字符串格式为,format="%Y-%m-%d"但可以随时更改。(例如。GetDate("2019-08-08 08:45", format="%Y-%m-%d %H:%M").current()
  3. GetDate("2019-08-08").get_month_first_day() 返回给定日期(字符串或对象)月份的第一天
  4. GetDate("2019-08-08").get_month_last_day() 返回上个月的给定日期
  5. GetDate("2019-08-08").minimum_time() 返回给定日期的开始日期
  6. GetDate("2019-08-08").maximum_time() 返回给定日期的一天结束
  7. GetDate("2019-08-08").time_delta_days({number_of_days})返回给定的日期+添加{天数}(您也可以调用:GetDate(timezone.now()).time_delta_days(-1)昨天)
  8. GetDate("2019-08-08").time_delta_haours({number_of_hours}) 与pt 7类似,但工作时间较长
  9. GetDate("2019-08-08").time_delta_seconds({number_of_seconds}) 类似于pt 7,但工作几秒钟

Generally you have’got an answer now but maybe my class I created will be also helpfull. For me it solves all my requirements I have ever had in my Pyhon projects.

class GetDate:
    def __init__(self, date, format="%Y-%m-%d"):
        self.tz = pytz.timezone("Europe/Warsaw")

        if isinstance(date, str):
            date = datetime.strptime(date, format)

        self.date = date.astimezone(self.tz)

    def time_delta_days(self, days):
        return self.date + timedelta(days=days)

    def time_delta_hours(self, hours):
        return self.date + timedelta(hours=hours)

    def time_delta_seconds(self, seconds):
        return self.date + timedelta(seconds=seconds)

    def get_minimum_time(self):
        return datetime.combine(self.date, time.min).astimezone(self.tz)

    def get_maximum_time(self):
        return datetime.combine(self.date, time.max).astimezone(self.tz)

    def get_month_first_day(self):
        return datetime(self.date.year, self.date.month, 1).astimezone(self.tz)

    def current(self):
        return self.date

    def get_month_last_day(self):
        lastDay = calendar.monthrange(self.date.year, self.date.month)[1]
        date = datetime(self.date.year, self.date.month, lastDay)
        return datetime.combine(date, time.max).astimezone(self.tz)

How to use it

  1. self.tz = pytz.timezone("Europe/Warsaw") – here you define Time Zone you want to use in project
  2. GetDate("2019-08-08").current() – this will convert your string date to time aware object with timezone you defined in pt 1. Default string format is format="%Y-%m-%d" but feel free to change it. (eg. GetDate("2019-08-08 08:45", format="%Y-%m-%d %H:%M").current())
  3. GetDate("2019-08-08").get_month_first_day() returns given date (string or object) month first day
  4. GetDate("2019-08-08").get_month_last_day() returns given date month last day
  5. GetDate("2019-08-08").minimum_time() returns given date day start
  6. GetDate("2019-08-08").maximum_time() returns given date day end
  7. GetDate("2019-08-08").time_delta_days({number_of_days}) returns given date + add {number of days} (you can also call: GetDate(timezone.now()).time_delta_days(-1) for yesterday)
  8. GetDate("2019-08-08").time_delta_haours({number_of_hours}) similar to pt 7 but working on hours
  9. GetDate("2019-08-08").time_delta_seconds({number_of_seconds}) similar to pt 7 but working on seconds

回答 10

有时我们需要使用按日期和日期进行搜索。如果我们使用date__range,那么我们需要添加1天和to_date,否则queryset将为空。

例:

从datetime导入timedelta

from_date = parse_date(request.POST [‘from_date’])

to_date = parse_date(request.POST [‘to_date’])+ timedelta(days = 1)

Attenance_list = models.DailyAttendance.objects.filter(attdate__range = [from_date,to_date])

Some time we need to use searching by from date & to date. If we use date__range then we need to add 1 days with to_date otherwise queryset will empty.

Example:

from datetime import timedelta

from_date = parse_date(request.POST[‘from_date’])

to_date = parse_date(request.POST[‘to_date’]) + timedelta(days=1)

attendance_list = models.DailyAttendance.objects.filter(attdate__range = [from_date, to_date])


Python日期字符串到日期对象

问题:Python日期字符串到日期对象

如何在python中将字符串转换为日期对象?

该字符串是:"24052010"(对应于格式:"%d%m%Y"

我不想要datetime.datetime对象,而是想要datetime.date。

How do I convert a string to a date object in python?

The string would be: "24052010" (corresponding to the format: "%d%m%Y")

I don’t want a datetime.datetime object, but rather a datetime.date.


回答 0

您可以strptimedatetimePython包中使用:

>>> import datetime
>>> datetime.datetime.strptime('24052010', "%d%m%Y").date()
datetime.date(2010, 5, 24)

You can use strptime in the datetime package of Python:

>>> import datetime
>>> datetime.datetime.strptime('24052010', "%d%m%Y").date()
datetime.date(2010, 5, 24)

回答 1

import datetime
datetime.datetime.strptime('24052010', '%d%m%Y').date()
import datetime
datetime.datetime.strptime('24052010', '%d%m%Y').date()

回答 2

直接相关的问题:

如果有的话

datetime.datetime.strptime("2015-02-24T13:00:00-08:00", "%Y-%B-%dT%H:%M:%S-%H:%M").date()

你会得到:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/_strptime.py", line 308, in _strptime
    format_regex = _TimeRE_cache.compile(format)
  File "/usr/local/lib/python2.7/_strptime.py", line 265, in compile
    return re_compile(self.pattern(format), IGNORECASE)
  File "/usr/local/lib/python2.7/re.py", line 194, in compile
    return _compile(pattern, flags)
  File "/usr/local/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: redefinition of group name 'H' as group 7; was group 4

并且您尝试了:

<-24T13:00:00-08:00", "%Y-%B-%dT%HH:%MM:%SS-%HH:%MM").date()

但是您仍然可以得到上面的追溯。

回答:

>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> parse("2015-02-24T13:00:00-08:00")
datetime.datetime(2015, 2, 24, 13, 0, tzinfo=tzoffset(None, -28800))

Directly related question:

What if you have

datetime.datetime.strptime("2015-02-24T13:00:00-08:00", "%Y-%B-%dT%H:%M:%S-%H:%M").date()

and you get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/_strptime.py", line 308, in _strptime
    format_regex = _TimeRE_cache.compile(format)
  File "/usr/local/lib/python2.7/_strptime.py", line 265, in compile
    return re_compile(self.pattern(format), IGNORECASE)
  File "/usr/local/lib/python2.7/re.py", line 194, in compile
    return _compile(pattern, flags)
  File "/usr/local/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: redefinition of group name 'H' as group 7; was group 4

and you tried:

<-24T13:00:00-08:00", "%Y-%B-%dT%HH:%MM:%SS-%HH:%MM").date()

but you still get the traceback above.

Answer:

>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> parse("2015-02-24T13:00:00-08:00")
datetime.datetime(2015, 2, 24, 13, 0, tzinfo=tzoffset(None, -28800))

回答 3

如果您懒惰并且不想与字符串文字打架,则可以使用该parser模块。

from dateutil import parser
dt = parser.parse("Jun 1 2005  1:33PM")
print(dt.year, dt.month, dt.day,dt.hour, dt.minute, dt.second)
>2005 6 1 13 33 0

只是一点说明,我们在尝试匹配any字符串表示形式时,它的速度比10倍慢strptime

If you are lazy and don’t want to fight with string literals, you can just go with the parser module.

from dateutil import parser
dt = parser.parse("Jun 1 2005  1:33PM")
print(dt.year, dt.month, dt.day,dt.hour, dt.minute, dt.second)
>2005 6 1 13 33 0

Just a side note, as we are trying to match any string representation, it is 10x slower than strptime


回答 4

您有一个像这样的日期字符串“ 24052010”,并且您想要这个日期对象,

from datetime import datetime
cus_date = datetime.strptime("24052010", "%d%m%Y").date()

此cus_date将为您提供日期对象。

您可以使用此方法从日期对象中检索日期字符串,

cus_date.strftime("%d%m%Y")

you have a date string like this, “24052010” and you want date object for this,

from datetime import datetime
cus_date = datetime.strptime("24052010", "%d%m%Y").date()

this cus_date will give you date object.

you can retrieve date string from your date object using this,

cus_date.strftime("%d%m%Y")

回答 5

还有一个叫做arrowpython的很棒的库,可以对python日期进行操作。

import arrow
import datetime

a = arrow.get('24052010', 'DMYYYY').date()
print(isinstance(a, datetime.date)) # True

There is another library called arrow really great to make manipulation on python date.

import arrow
import datetime

a = arrow.get('24052010', 'DMYYYY').date()
print(isinstance(a, datetime.date)) # True

回答 6

使用时间模块转换数据。

程式码片段:

import time 
tring='20150103040500'
var = int(time.mktime(time.strptime(tring, '%Y%m%d%H%M%S')))
print var

Use time module to convert data.

Code snippet:

import time 
tring='20150103040500'
var = int(time.mktime(time.strptime(tring, '%Y%m%d%H%M%S')))
print var

如何获得每月的最后一天?

问题:如何获得每月的最后一天?

是否可以使用Python的标准库轻松确定(即调用一个函数)给定月份的最后一天?

如果标准库不支持该功能,dateutil包是否支持此功能?

Is there a way using Python’s standard library to easily determine (i.e. one function call) the last day of a given month?

If the standard library doesn’t support that, does the dateutil package support this?


回答 0

查看该calendar模块文档时,我没有注意到这一点,但是称为的方法monthrange提供了以下信息:

monthrange(year,month)
    返回指定年份和月份的月份的第一天的工作日以及月份中的天数。

>>> import calendar
>>> calendar.monthrange(2002,1)
(1, 31)
>>> calendar.monthrange(2008,2)
(4, 29)
>>> calendar.monthrange(2100,2)
(0, 28)

所以:

calendar.monthrange(year, month)[1]

似乎是最简单的方法。

明确一点,也monthrange支持supports年:

>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)

我以前的答案仍然有效,但显然不是最佳选择。

I didn’t notice this earlier when I was looking at the documentation for the calendar module, but a method called monthrange provides this information:

monthrange(year, month)
    Returns weekday of first day of the month and number of days in month, for the specified year and month.

>>> import calendar
>>> calendar.monthrange(2002,1)
(1, 31)
>>> calendar.monthrange(2008,2)
(4, 29)
>>> calendar.monthrange(2100,2)
(0, 28)

so:

calendar.monthrange(year, month)[1]

seems like the simplest way to go.

Just to be clear, monthrange supports leap years as well:

>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)

My previous answer still works, but is clearly suboptimal.


回答 1

如果您不想导入calendar模块,那么一个简单的两步函数也可以是:

import datetime

def last_day_of_month(any_day):
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)  # this will never fail
    return next_month - datetime.timedelta(days=next_month.day)

输出:

>>> for month in range(1, 13):
...     print last_day_of_month(datetime.date(2012, month, 1))
...
2012-01-31
2012-02-29
2012-03-31
2012-04-30
2012-05-31
2012-06-30
2012-07-31
2012-08-31
2012-09-30
2012-10-31
2012-11-30
2012-12-31

If you don’t want to import the calendar module, a simple two-step function can also be:

import datetime

def last_day_of_month(any_day):
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)  # this will never fail
    return next_month - datetime.timedelta(days=next_month.day)

Outputs:

>>> for month in range(1, 13):
...     print last_day_of_month(datetime.date(2012, month, 1))
...
2012-01-31
2012-02-29
2012-03-31
2012-04-30
2012-05-31
2012-06-30
2012-07-31
2012-08-31
2012-09-30
2012-10-31
2012-11-30
2012-12-31

回答 2

编辑:请参阅@Blair Conrad的答案以获得更清洁的解决方案


>>> import datetime
>>> datetime.date(2000, 2, 1) - datetime.timedelta(days=1)
datetime.date(2000, 1, 31)

EDIT: See @Blair Conrad’s answer for a cleaner solution


>>> import datetime
>>> datetime.date(2000, 2, 1) - datetime.timedelta(days=1)
datetime.date(2000, 1, 31)

回答 3

dateutil.relativedelta(使用pip软件包python-datetutil)实际上很容易。day=31始终会返回该月的最后一天。

例:

from datetime import datetime
from dateutil.relativedelta import relativedelta

date_in_feb = datetime.datetime(2013, 2, 21)
print datetime.datetime(2013, 2, 21) + relativedelta(day=31)  # End-of-month
>>> datetime.datetime(2013, 2, 28, 0, 0)

This is actually pretty easy with dateutil.relativedelta (package python-datetutil for pip). day=31 will always always return the last day of the month.

Example:

from datetime import datetime
from dateutil.relativedelta import relativedelta

date_in_feb = datetime.datetime(2013, 2, 21)
print datetime.datetime(2013, 2, 21) + relativedelta(day=31)  # End-of-month
>>> datetime.datetime(2013, 2, 28, 0, 0)

回答 4

编辑:看到我的其他答案。它的实现比该方法更好,我留在这里是为了防止有人感兴趣地看一看如何“滚动自己的”计算器。

@John Millikin提供了一个很好的答案,增加了计算下个月第一天的复杂性。

以下内容并不是特别优雅,但是要弄清楚任何给定日期所在的月份的最后一天,您可以尝试:

def last_day_of_month(date):
    if date.month == 12:
        return date.replace(day=31)
    return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)

>>> last_day_of_month(datetime.date(2002, 1, 17))
datetime.date(2002, 1, 31)
>>> last_day_of_month(datetime.date(2002, 12, 9))
datetime.date(2002, 12, 31)
>>> last_day_of_month(datetime.date(2008, 2, 14))
datetime.date(2008, 2, 29)

EDIT: see my other answer. It has a better implementation than this one, which I leave here just in case someone’s interested in seeing how one might “roll your own” calculator.

@John Millikin gives a good answer, with the added complication of calculating the first day of the next month.

The following isn’t particularly elegant, but to figure out the last day of the month that any given date lives in, you could try:

def last_day_of_month(date):
    if date.month == 12:
        return date.replace(day=31)
    return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)

>>> last_day_of_month(datetime.date(2002, 1, 17))
datetime.date(2002, 1, 31)
>>> last_day_of_month(datetime.date(2002, 12, 9))
datetime.date(2002, 12, 31)
>>> last_day_of_month(datetime.date(2008, 2, 14))
datetime.date(2008, 2, 29)

回答 5

使用dateutil.relativedelta您会得到这样的月份的最后日期:

from dateutil.relativedelta import relativedelta
last_date_of_month = datetime(mydate.year, mydate.month, 1) + relativedelta(months=1, days=-1)

这个想法是获取月份的第一天,并relativedelta习惯于提前一个月再返回一天,这样您就可以获得想要的月份的最后一天。

Using dateutil.relativedelta you would get last date of month like this:

from dateutil.relativedelta import relativedelta
last_date_of_month = datetime(mydate.year, mydate.month, 1) + relativedelta(months=1, days=-1)

The idea is to get the first day of the month and use relativedelta to go 1 month ahead and 1 day back so you would get the last day of the month you wanted.


回答 6

另一个解决方案是做这样的事情:

from datetime import datetime

def last_day_of_month(year, month):
    """ Work out the last day of the month """
    last_days = [31, 30, 29, 28, 27]
    for i in last_days:
        try:
            end = datetime(year, month, i)
        except ValueError:
            continue
        else:
            return end.date()
    return None

并使用如下功能:

>>> 
>>> last_day_of_month(2008, 2)
datetime.date(2008, 2, 29)
>>> last_day_of_month(2009, 2)
datetime.date(2009, 2, 28)
>>> last_day_of_month(2008, 11)
datetime.date(2008, 11, 30)
>>> last_day_of_month(2008, 12)
datetime.date(2008, 12, 31)

Another solution would be to do something like this:

from datetime import datetime

def last_day_of_month(year, month):
    """ Work out the last day of the month """
    last_days = [31, 30, 29, 28, 27]
    for i in last_days:
        try:
            end = datetime(year, month, i)
        except ValueError:
            continue
        else:
            return end.date()
    return None

And use the function like this:

>>> 
>>> last_day_of_month(2008, 2)
datetime.date(2008, 2, 29)
>>> last_day_of_month(2009, 2)
datetime.date(2009, 2, 28)
>>> last_day_of_month(2008, 11)
datetime.date(2008, 11, 30)
>>> last_day_of_month(2008, 12)
datetime.date(2008, 12, 31)

回答 7

from datetime import timedelta
(any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)
from datetime import timedelta
(any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)

回答 8

>>> import datetime
>>> import calendar
>>> date  = datetime.datetime.now()

>>> print date
2015-03-06 01:25:14.939574

>>> print date.replace(day = 1)
2015-03-01 01:25:14.939574

>>> print date.replace(day = calendar.monthrange(date.year, date.month)[1])
2015-03-31 01:25:14.939574
>>> import datetime
>>> import calendar
>>> date  = datetime.datetime.now()

>>> print date
2015-03-06 01:25:14.939574

>>> print date.replace(day = 1)
2015-03-01 01:25:14.939574

>>> print date.replace(day = calendar.monthrange(date.year, date.month)[1])
2015-03-31 01:25:14.939574

回答 9

如果您愿意使用外部库,请访问http://crsmithdev.com/arrow/

然后,您可以使用以下命令获取月份的最后一天:

import arrow
arrow.utcnow().ceil('month').date()

这将返回一个日期对象,您可以随后对其进行操作。

if you are willing to use an external library, check out http://crsmithdev.com/arrow/

U can then get the last day of the month with:

import arrow
arrow.utcnow().ceil('month').date()

This returns a date object which you can then do your manipulation.


回答 10

要获取该月的最后日期,我们需要执行以下操作:

from datetime import date, timedelta
import calendar
last_day = date.today().replace(day=calendar.monthrange(date.today().year, date.today().month)[1])

现在解释一下我们在这里做什么,我们将其分为两部分:

首先是获取当月的天数,我们使用Blair Conrad已经提到他的解决方案的monthrange

calendar.monthrange(date.today().year, date.today().month)[1]

二是让我们的帮助下做的最后日期本身代替

>>> date.today()
datetime.date(2017, 1, 3)
>>> date.today().replace(day=31)
datetime.date(2017, 1, 31)

当我们按顶部所述将它们组合在一起时,便得到了动态解决方案。

To get the last date of the month we do something like this:

from datetime import date, timedelta
import calendar
last_day = date.today().replace(day=calendar.monthrange(date.today().year, date.today().month)[1])

Now to explain what we are doing here we will break it into two parts:

first is getting the number of days of the current month for which we use monthrange which Blair Conrad has already mentioned his solution:

calendar.monthrange(date.today().year, date.today().month)[1]

second is getting the last date itself which we do with the help of replace e.g

>>> date.today()
datetime.date(2017, 1, 3)
>>> date.today().replace(day=31)
datetime.date(2017, 1, 31)

and when we combine them as mentioned on the top we get a dynamic solution.


回答 11

在Python 3.7中,有未记录的calendar.monthlen(year, month)函数

>>> calendar.monthlen(2002, 1)
31
>>> calendar.monthlen(2008, 2)
29
>>> calendar.monthlen(2100, 2)
28

它等效于记录的calendar.monthrange(year, month)[1]呼叫

In Python 3.7 there is the undocumented calendar.monthlen(year, month) function:

>>> calendar.monthlen(2002, 1)
31
>>> calendar.monthlen(2008, 2)
29
>>> calendar.monthlen(2100, 2)
28

It is equivalent to the documented calendar.monthrange(year, month)[1] call.


回答 12

import datetime

now = datetime.datetime.now()
start_month = datetime.datetime(now.year, now.month, 1)
date_on_next_month = start_month + datetime.timedelta(35)
start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)
last_day_month = start_next_month - datetime.timedelta(1)
import datetime

now = datetime.datetime.now()
start_month = datetime.datetime(now.year, now.month, 1)
date_on_next_month = start_month + datetime.timedelta(35)
start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)
last_day_month = start_next_month - datetime.timedelta(1)

回答 13

使用熊猫!

def isMonthEnd(date):
    return date + pd.offsets.MonthEnd(0) == date

isMonthEnd(datetime(1999, 12, 31))
True
isMonthEnd(pd.Timestamp('1999-12-31'))
True
isMonthEnd(pd.Timestamp(1965, 1, 10))
False

Use pandas!

def isMonthEnd(date):
    return date + pd.offsets.MonthEnd(0) == date

isMonthEnd(datetime(1999, 12, 31))
True
isMonthEnd(pd.Timestamp('1999-12-31'))
True
isMonthEnd(pd.Timestamp(1965, 1, 10))
False

回答 14

对我来说,这是最简单的方法:

selected_date = date(some_year, some_month, some_day)

if selected_date.month == 12: # December
     last_day_selected_month = date(selected_date.year, selected_date.month, 31)
else:
     last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)

For me it’s the simplest way:

selected_date = date(some_year, some_month, some_day)

if selected_date.month == 12: # December
     last_day_selected_month = date(selected_date.year, selected_date.month, 31)
else:
     last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)

回答 15

最简单的方法(无需导入日历)是获取下个月的第一天,然后从中减去一天。

import datetime as dt
from dateutil.relativedelta import relativedelta

thisDate = dt.datetime(2017, 11, 17)

last_day_of_the_month = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)
print last_day_of_the_month

输出:

datetime.datetime(2017, 11, 30, 0, 0)

PS:与该import calendar方法相比,此代码运行速度更快;见下文:

import datetime as dt
import calendar
from dateutil.relativedelta import relativedelta

someDates = [dt.datetime.today() - dt.timedelta(days=x) for x in range(0, 10000)]

start1 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)

print ('Time Spent= ', dt.datetime.now() - start1)


start2 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, 
                          thisDate.month, 
                          calendar.monthrange(thisDate.year, thisDate.month)[1])

print ('Time Spent= ', dt.datetime.now() - start2)

输出:

Time Spent=  0:00:00.097814
Time Spent=  0:00:00.109791

此代码假定您需要该月最后一天的日期(即,不仅是DD部分,而且是整个YYYYMMDD日期)

The easiest way (without having to import calendar), is to get the first day of the next month, and then subtract a day from it.

import datetime as dt
from dateutil.relativedelta import relativedelta

thisDate = dt.datetime(2017, 11, 17)

last_day_of_the_month = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)
print last_day_of_the_month

Output:

datetime.datetime(2017, 11, 30, 0, 0)

PS: This code runs faster as compared to the import calendarapproach; see below:

import datetime as dt
import calendar
from dateutil.relativedelta import relativedelta

someDates = [dt.datetime.today() - dt.timedelta(days=x) for x in range(0, 10000)]

start1 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)

print ('Time Spent= ', dt.datetime.now() - start1)


start2 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, 
                          thisDate.month, 
                          calendar.monthrange(thisDate.year, thisDate.month)[1])

print ('Time Spent= ', dt.datetime.now() - start2)

OUTPUT:

Time Spent=  0:00:00.097814
Time Spent=  0:00:00.109791

This code assumes that you want the date of the last day of the month (i.e., not just the DD part, but the entire YYYYMMDD date)


回答 16

这是另一个答案。无需额外的程序包。

datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)

获取下个月的第一天并从中减去一天。

Here is another answer. No extra packages required.

datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)

Get the first day of the next month and subtract a day from it.


回答 17

您可以自己计算结束日期。简单的逻辑是从下个月的start_date减去一天。:)

因此,编写一个自定义方法,

import datetime

def end_date_of_a_month(date):


    start_date_of_this_month = date.replace(day=1)

    month = start_date_of_this_month.month
    year = start_date_of_this_month.year
    if month == 12:
        month = 1
        year += 1
    else:
        month += 1
    next_month_start_date = start_date_of_this_month.replace(month=month, year=year)

    this_month_end_date = next_month_start_date - datetime.timedelta(days=1)
    return this_month_end_date

打电话

end_date_of_a_month(datetime.datetime.now().date())

它将返回本月的结束日期。将任何日期传递给此功能。返回该月的结束日期。

You can calculate the end date yourself. the simple logic is to subtract a day from the start_date of next month. :)

So write a custom method,

import datetime

def end_date_of_a_month(date):


    start_date_of_this_month = date.replace(day=1)

    month = start_date_of_this_month.month
    year = start_date_of_this_month.year
    if month == 12:
        month = 1
        year += 1
    else:
        month += 1
    next_month_start_date = start_date_of_this_month.replace(month=month, year=year)

    this_month_end_date = next_month_start_date - datetime.timedelta(days=1)
    return this_month_end_date

Calling,

end_date_of_a_month(datetime.datetime.now().date())

It will return the end date of this month. Pass any date to this function. returns you the end date of that month.


回答 18

您可以使用relativedelta https://dateutil.readthedocs.io/en/stable/relativedelta.html month_end = <your datetime value within the month> + relativedelta(day=31) 来给您最后的一天。

you can use relativedelta https://dateutil.readthedocs.io/en/stable/relativedelta.html month_end = <your datetime value within the month> + relativedelta(day=31) that will give you the last day.


回答 19

仅使用标准日期时间库,这对我来说是最简单的解决方案:

import datetime

def get_month_end(dt):
    first_of_month = datetime.datetime(dt.year, dt.month, 1)
    next_month_date = first_of_month + datetime.timedelta(days=32)
    new_dt = datetime.datetime(next_month_date.year, next_month_date.month, 1)
    return new_dt - datetime.timedelta(days=1)

This is the simplest solution for me using just the standard datetime library:

import datetime

def get_month_end(dt):
    first_of_month = datetime.datetime(dt.year, dt.month, 1)
    next_month_date = first_of_month + datetime.timedelta(days=32)
    new_dt = datetime.datetime(next_month_date.year, next_month_date.month, 1)
    return new_dt - datetime.timedelta(days=1)

回答 20

这没有解决主要问题,但是使用一个月中的最后一个工作日的一个不错的技巧是使用calendar.monthcalendar,该方法返回一个日期矩阵,将星期一作为第一列,将星期日作为最后一个列。

# Some random date.
some_date = datetime.date(2012, 5, 23)

# Get last weekday
last_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max()

print last_weekday
31

整个过程[0:-2]就是刮掉周末专栏文章,然后将它们扔掉。月份以外的日期用0表示,因此最大值实际上会忽略它们。

使用的numpy.ravel是不是绝对必要的,但我不喜欢依靠单纯的惯例numpy.ndarray.max将压平的数组,如果没有被告知哪个轴计算过。

This does not address the main question, but one nice trick to get the last weekday in a month is to use calendar.monthcalendar, which returns a matrix of dates, organized with Monday as the first column through Sunday as the last.

# Some random date.
some_date = datetime.date(2012, 5, 23)

# Get last weekday
last_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max()

print last_weekday
31

The whole [0:-2] thing is to shave off the weekend columns and throw them out. Dates that fall outside of the month are indicated by 0, so the max effectively ignores them.

The use of numpy.ravel is not strictly necessary, but I hate relying on the mere convention that numpy.ndarray.max will flatten the array if not told which axis to calculate over.


回答 21

import calendar
from time import gmtime, strftime
calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]

输出:

31



这将打印当前月份的最后一天。在此示例中,日期是2016年5月15日。因此您的输出可能会有所不同,但是输出将是当月的几天。如果您想通过运行每日Cron作业来检查每月的最后一天,那就太好了。

所以:

import calendar
from time import gmtime, strftime
lastDay = calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]
today = strftime("%d", gmtime())
lastDay == today

输出:

False

除非是每月的最后一天。

import calendar
from time import gmtime, strftime
calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]

Output:

31



This will print the last day of whatever the current month is. In this example it was 15th May, 2016. So your output may be different, however the output will be as many days that the current month is. Great if you want to check the last day of the month by running a daily cron job.

So:

import calendar
from time import gmtime, strftime
lastDay = calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]
today = strftime("%d", gmtime())
lastDay == today

Output:

False

Unless it IS the last day of the month.


回答 22

我喜欢这样

import datetime
import calendar

date=datetime.datetime.now()
month_end_date=datetime.datetime(date.year,date.month,1) + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1] - 1)

I prefer this way

import datetime
import calendar

date=datetime.datetime.now()
month_end_date=datetime.datetime(date.year,date.month,1) + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1] - 1)

回答 23

如果要创建自己的小函数,这是一个很好的起点:

def eomday(year, month):
    """returns the number of days in a given month"""
    days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    d = days_per_month[month - 1]
    if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
        d = 29
    return d

为此,您必须了解the年的规则:

  • 每四年
  • 每100年除外
  • 但是每400年一次

If you want to make your own small function, this is a good starting point:

def eomday(year, month):
    """returns the number of days in a given month"""
    days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    d = days_per_month[month - 1]
    if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
        d = 29
    return d

For this you have to know the rules for the leap years:

  • every fourth year
  • with the exception of every 100 year
  • but again every 400 years

回答 24

如果输入日期范围,则可以使用以下方法:

def last_day_of_month(any_days):
    res = []
    for any_day in any_days:
        nday = any_day.days_in_month -any_day.day
        res.append(any_day + timedelta(days=nday))
    return res

If you pass in a date range, you can use this:

def last_day_of_month(any_days):
    res = []
    for any_day in any_days:
        nday = any_day.days_in_month -any_day.day
        res.append(any_day + timedelta(days=nday))
    return res

回答 25

“ get_last_day_of_month(dt)”下面的代码中,将为您提供此日期,日期格式为“ YYYY-MM-DD”。

import datetime

def DateTime( d ):
    return datetime.datetime.strptime( d, '%Y-%m-%d').date()

def RelativeDate( start, num_days ):
    d = DateTime( start )
    return str( d + datetime.timedelta( days = num_days ) )

def get_first_day_of_month( dt ):
    return dt[:-2] + '01'

def get_last_day_of_month( dt ):
    fd = get_first_day_of_month( dt )
    fd_next_month = get_first_day_of_month( RelativeDate( fd, 31 ) )
    return RelativeDate( fd_next_month, -1 )

In the code below ‘get_last_day_of_month(dt)’ will give you this, with date in string format like ‘YYYY-MM-DD’.

import datetime

def DateTime( d ):
    return datetime.datetime.strptime( d, '%Y-%m-%d').date()

def RelativeDate( start, num_days ):
    d = DateTime( start )
    return str( d + datetime.timedelta( days = num_days ) )

def get_first_day_of_month( dt ):
    return dt[:-2] + '01'

def get_last_day_of_month( dt ):
    fd = get_first_day_of_month( dt )
    fd_next_month = get_first_day_of_month( RelativeDate( fd, 31 ) )
    return RelativeDate( fd_next_month, -1 )

回答 26

最简单的方法是使用datetime和一些日期数学,例如从下个月的第一天减去一天:

import datetime

def last_day_of_month(d: datetime.date) -> datetime.date:
    return (
        datetime.date(d.year + d.month//12, d.month % 12 + 1, 1) -
        datetime.timedelta(days=1)
    )

或者,您可以calendar.monthrange()用来获取一个月中的天数(考虑leap年)并相应地更新日期:

import calendar, datetime

def last_day_of_month(d: datetime.date) -> datetime.date:
    return d.replace(day=calendar.monthrange(d.year, d.month)[1])

快速基准测试表明,第一个版本的速度明显更快:

In [14]: today = datetime.date.today()

In [15]: %timeit last_day_of_month_dt(today)
918 ns ± 3.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [16]: %timeit last_day_of_month_calendar(today)
1.4 µs ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

The simplest way is to use datetime and some date math, e.g. subtract a day from the first day of the next month:

import datetime

def last_day_of_month(d: datetime.date) -> datetime.date:
    return (
        datetime.date(d.year + d.month//12, d.month % 12 + 1, 1) -
        datetime.timedelta(days=1)
    )

Alternatively, you could use calendar.monthrange() to get the number of days in a month (taking leap years into account) and update the date accordingly:

import calendar, datetime

def last_day_of_month(d: datetime.date) -> datetime.date:
    return d.replace(day=calendar.monthrange(d.year, d.month)[1])

A quick benchmark shows that the first version is noticeably faster:

In [14]: today = datetime.date.today()

In [15]: %timeit last_day_of_month_dt(today)
918 ns ± 3.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [16]: %timeit last_day_of_month_calendar(today)
1.4 µs ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

回答 27

这是一个很长的版本(易于理解),但是照顾了leap年。

干杯,JK

def last_day_month(year, month):
    leap_year_flag = 0
    end_dates = {
        1: 31,
        2: 28,
        3: 31,
        4: 30,
        5: 31,
        6: 30,
        7: 31,
        8: 31,
        9: 30,
        10: 31,
        11: 30,
        12: 31
    }

    # Checking for regular leap year    
    if year % 4 == 0:
        leap_year_flag = 1
    else:
        leap_year_flag = 0

    # Checking for century leap year    
    if year % 100 == 0:
        if year % 400 == 0:
            leap_year_flag = 1
        else:
            leap_year_flag = 0
    else:
        pass

    # return end date of the year-month
    if leap_year_flag == 1 and month == 2:
        return 29
    elif leap_year_flag == 1 and month != 2:
        return end_dates[month]
    else:
        return end_dates[month]

Here is a long (easy to understand) version but takes care of leap years.

cheers, JK

def last_day_month(year, month):
    leap_year_flag = 0
    end_dates = {
        1: 31,
        2: 28,
        3: 31,
        4: 30,
        5: 31,
        6: 30,
        7: 31,
        8: 31,
        9: 30,
        10: 31,
        11: 30,
        12: 31
    }

    # Checking for regular leap year    
    if year % 4 == 0:
        leap_year_flag = 1
    else:
        leap_year_flag = 0

    # Checking for century leap year    
    if year % 100 == 0:
        if year % 400 == 0:
            leap_year_flag = 1
        else:
            leap_year_flag = 0
    else:
        pass

    # return end date of the year-month
    if leap_year_flag == 1 and month == 2:
        return 29
    elif leap_year_flag == 1 and month != 2:
        return end_dates[month]
    else:
        return end_dates[month]

回答 28

这是一个基于解决方案的python lambdas:

next_month = lambda y, m, d: (y, m + 1, 1) if m + 1 < 13 else ( y+1 , 1, 1)
month_end  = lambda dte: date( *next_month( *dte.timetuple()[:3] ) ) - timedelta(days=1)

next_month拉姆达发现到明年下个月的第一天的元组表示,和卷。该month_end拉姆达转换日期(dte)的元组,应用next_month和创造新的日期。然后,“月底”就是下个月的第一天减去timedelta(days=1)

Here is a solution based python lambdas:

next_month = lambda y, m, d: (y, m + 1, 1) if m + 1 < 13 else ( y+1 , 1, 1)
month_end  = lambda dte: date( *next_month( *dte.timetuple()[:3] ) ) - timedelta(days=1)

The next_month lambda finds the tuple representation of the first day of the next month, and rolls over to the next year. The month_end lambda transforms a date (dte) to a tuple, applies next_month and creates a new date. Then the “month’s end” is just the next month’s first day minus timedelta(days=1).