标签归档:datetime

如何从日期中减去一天?

问题:如何从日期中减去一天?

我有一个Python datetime.datetime对象。减去一天的最佳方法是什么?

I have a Python datetime.datetime object. What is the best way to subtract one day?


回答 0

您可以使用timedelta对象:

from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)

You can use a timedelta object:

from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)

回答 1

减去 datetime.timedelta(days=1)

Subtract datetime.timedelta(days=1)


回答 2

如果您的Python日期时间对象可识别时区,则应注意避免DST转换周围的错误(或由于其他原因导致UTC偏移量发生变化):

from datetime import datetime, timedelta
from tzlocal import get_localzone # pip install tzlocal

DAY = timedelta(1)
local_tz = get_localzone()   # get local timezone
now = datetime.now(local_tz) # get timezone-aware datetime object
day_ago = local_tz.normalize(now - DAY) # exactly 24 hours ago, time may differ
naive = now.replace(tzinfo=None) - DAY # same time
yesterday = local_tz.localize(naive, is_dst=None) # but elapsed hours may differ

在一般情况下,day_agoyesterday如果UTC偏移量本地时区中的最后一天发生了变化可能会有所不同。

例如,夏令时/夏令时在美国/洛杉矶时区的Sun 2-Nov-2014的02:00:00 AM结束,因此,如果:

import pytz # pip install pytz

local_tz = pytz.timezone('America/Los_Angeles')
now = local_tz.localize(datetime(2014, 11, 2, 10), is_dst=None)
# 2014-11-02 10:00:00 PST-0800

然后day_agoyesterday不同:

  • day_ago恰好是24小时前(相对于now),但在上午11点而不是上午10点now
  • yesterday是昨天上午10点,但是是25小时前(相对于now),而不是24小时。

pendulum模块自动处理它:

>>> import pendulum  # $ pip install pendulum

>>> now = pendulum.create(2014, 11, 2, 10, tz='America/Los_Angeles')
>>> day_ago = now.subtract(hours=24)  # exactly 24 hours ago
>>> yesterday = now.subtract(days=1)  # yesterday at 10 am but it is 25 hours ago

>>> (now - day_ago).in_hours()
24
>>> (now - yesterday).in_hours()
25

>>> now
<Pendulum [2014-11-02T10:00:00-08:00]>
>>> day_ago
<Pendulum [2014-11-01T11:00:00-07:00]>
>>> yesterday
<Pendulum [2014-11-01T10:00:00-07:00]>

If your Python datetime object is timezone-aware than you should be careful to avoid errors around DST transitions (or changes in UTC offset for other reasons):

from datetime import datetime, timedelta
from tzlocal import get_localzone # pip install tzlocal

DAY = timedelta(1)
local_tz = get_localzone()   # get local timezone
now = datetime.now(local_tz) # get timezone-aware datetime object
day_ago = local_tz.normalize(now - DAY) # exactly 24 hours ago, time may differ
naive = now.replace(tzinfo=None) - DAY # same time
yesterday = local_tz.localize(naive, is_dst=None) # but elapsed hours may differ

In general, day_ago and yesterday may differ if UTC offset for the local timezone has changed in the last day.

For example, daylight saving time/summer time ends on Sun 2-Nov-2014 at 02:00:00 A.M. in America/Los_Angeles timezone therefore if:

import pytz # pip install pytz

local_tz = pytz.timezone('America/Los_Angeles')
now = local_tz.localize(datetime(2014, 11, 2, 10), is_dst=None)
# 2014-11-02 10:00:00 PST-0800

then day_ago and yesterday differ:

  • day_ago is exactly 24 hours ago (relative to now) but at 11 am, not at 10 am as now
  • yesterday is yesterday at 10 am but it is 25 hours ago (relative to now), not 24 hours.

pendulum module handles it automatically:

>>> import pendulum  # $ pip install pendulum

>>> now = pendulum.create(2014, 11, 2, 10, tz='America/Los_Angeles')
>>> day_ago = now.subtract(hours=24)  # exactly 24 hours ago
>>> yesterday = now.subtract(days=1)  # yesterday at 10 am but it is 25 hours ago

>>> (now - day_ago).in_hours()
24
>>> (now - yesterday).in_hours()
25

>>> now
<Pendulum [2014-11-02T10:00:00-08:00]>
>>> day_ago
<Pendulum [2014-11-01T11:00:00-07:00]>
>>> yesterday
<Pendulum [2014-11-01T10:00:00-07:00]>

回答 3

只是为了阐明对它有帮助的替代方法和用例:

  • 从当前日期时间减去1天:
from datetime import datetime, timedelta
print datetime.now() + timedelta(days=-1)  # Here, I am adding a negative timedelta
  • 在案例中很有用,如果您想增加5天并从当前日期时间中减去5小时。即从现在算起5天,但少5个小时的日期时间是什么?
from datetime import datetime, timedelta
print datetime.now() + timedelta(days=5, hours=-5)

它可以类似地与其他参数一起使用,例如秒,周等

Just to Elaborate an alternate method and a Use case for which it is helpful:

  • Subtract 1 day from current datetime:
from datetime import datetime, timedelta
print datetime.now() + timedelta(days=-1)  # Here, I am adding a negative timedelta
  • Useful in the Case, If you want to add 5 days and subtract 5 hours from current datetime. i.e. What is the Datetime 5 days from now but 5 hours less ?
from datetime import datetime, timedelta
print datetime.now() + timedelta(days=5, hours=-5)

It can similarly be used with other parameters e.g. seconds, weeks etc


回答 4

当我想计算上个月的第一天/最后一天或其他相对时间增量等时,我也喜欢使用另一个好函数。

从relativedelta功能dateutil功能(一个强大的扩展到datetime LIB)

import datetime as dt
from dateutil.relativedelta import relativedelta
#get first and last day of this and last month)
today = dt.date.today()
first_day_this_month = dt.date(day=1, month=today.month, year=today.year)
last_day_last_month = first_day_this_month - relativedelta(days=1)
print (first_day_this_month, last_day_last_month)

>2015-03-01 2015-02-28

Also just another nice function i like to use when i want to compute i.e. first/last day of the last month or other relative timedeltas etc. …

The relativedelta function from dateutil function (a powerful extension to the datetime lib)

import datetime as dt
from dateutil.relativedelta import relativedelta
#get first and last day of this and last month)
today = dt.date.today()
first_day_this_month = dt.date(day=1, month=today.month, year=today.year)
last_day_last_month = first_day_this_month - relativedelta(days=1)
print (first_day_this_month, last_day_last_month)

>2015-03-01 2015-02-28

回答 5

存在温和的箭头模块

import arrow
utc = arrow.utcnow()
utc_yesterday = utc.shift(days=-1)
print(utc, '\n', utc_yesterday)

输出:

2017-04-06T11:17:34.431397+00:00 
 2017-04-05T11:17:34.431397+00:00

Genial arrow module exists

import arrow
utc = arrow.utcnow()
utc_yesterday = utc.shift(days=-1)
print(utc, '\n', utc_yesterday)

output:

2017-04-06T11:17:34.431397+00:00 
 2017-04-05T11:17:34.431397+00:00

如何以常规格式打印日期?

问题:如何以常规格式打印日期?

这是我的代码:

import datetime
today = datetime.date.today()
print(today)

打印:2008-11-22这正是我想要的。

但是,我有一个列表要附加到该列表中,然后突然所有内容都变得“异常”。这是代码:

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist)

打印以下内容:

[datetime.date(2008, 11, 22)]

我怎样才能得到一个简单的约会2008-11-22

This is my code:

import datetime
today = datetime.date.today()
print(today)

This prints: 2008-11-22 which is exactly what I want.

But, I have a list I’m appending this to and then suddenly everything goes “wonky”. Here is the code:

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist)

This prints the following:

[datetime.date(2008, 11, 22)]

How can I get just a simple date like 2008-11-22?


回答 0

为什么:日期是对象

在Python中,日期是对象。因此,当您操作它们时,您将操作对象,而不是字符串,时间戳或其他任何对象。

Python中的任何对象都有两个字符串表示形式:

  • 可以使用str()函数获取“打印”所使用的常规表示形式。在大多数情况下,它是最常见的人类可读格式,用于简化显示。所以str(datetime.datetime(2008, 11, 22, 19, 53, 42))给你'2008-11-22 19:53:42'

  • 用于表示对象性质(作为数据)的替代表示。它可以使用该repr()函数获得,并且很容易知道在开发或调试时要处理的数据类型。repr(datetime.datetime(2008, 11, 22, 19, 53, 42))给你'datetime.datetime(2008, 11, 22, 19, 53, 42)'

发生的事情是,当您使用“打印”打印日期时,会使用它,str()以便可以看到一个不错的日期字符串。但是在打印后mylist,您已经打印了一个对象列表,Python尝试使用来表示数据集repr()

方法:您想怎么做?

好吧,当您操作日期时,请一直使用日期对象。他们获得了数千种有用的方法,并且大多数Python API都希望日期成为对象。

要显示它们时,只需使用str()。在Python中,良好的做法是显式转换所有内容。因此,仅在打印时,使用即可获取日期的字符串表示形式str(date)

最后一件事。当您尝试打印日期时,您打印了mylist。如果要打印日期,则必须打印日期对象,而不是其容器(列表)。

EG,您想将所有日期打印在列表中:

for date in mylist :
    print str(date)

请注意,在这种特定情况下,您甚至可以省略,str()因为打印将为您使用它。但这不应该成为一种习惯:-)

实际案例,使用您的代码

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22

# It's better to always use str() because :

print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22

print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects

print "This is a new day : " + str(mylist[0]) 
>>> This is a new day : 2008-11-22

高级日期格式

日期具有默认表示形式,但是您可能需要以特定格式打印日期。在这种情况下,您可以使用strftime()方法获得自定义的字符串表示形式。

strftime() 需要一个字符串模式来说明如何格式化日期。

EG:

print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'

a之后的所有字母"%"代表某种格式:

  • %d 是天数
  • %m 是月份号
  • %b 是月份的缩写
  • %y 是年份的后两位数字
  • %Y 是整年

等等

查看官方文档McCutchen的快速参考资料,您可能一无所知

PEP3101开始,每个对象都可以具有自己的格式,该格式可以由任何字符串的方法格式自动使用。对于日期时间,格式与strftime中使用的格式相同。因此,您可以像上面这样做:

print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'

这种形式的优点是您还可以同时转换其他对象。
引入了格式化字符串文字(自Python 3.6,2016-12-23起),可以这样写:

import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'

本土化

如果您以正确的方式使用日期,日期会自动适应当地的语言和文化,但这有点复杂。也许是关于SO(堆栈溢出)的另一个问题;-)

The WHY: dates are objects

In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings, not timestamps nor anything.

Any object in Python have TWO string representations:

  • The regular representation that is used by “print”, can be get using the str() function. It is most of the time the most common human readable format and is used to ease display. So str(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you '2008-11-22 19:53:42'.

  • The alternative representation that is used to represent the object nature (as a data). It can be get using the repr() function and is handy to know what kind of data your manipulating while you are developing or debugging. repr(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you 'datetime.datetime(2008, 11, 22, 19, 53, 42)'.

What happened is that when you have printed the date using “print”, it used str() so you could see a nice date string. But when you have printed mylist, you have printed a list of objects and Python tried to represent the set of data, using repr().

The How: what do you want to do with that?

Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.

When you want to display them, just use str(). In Python, the good practice is to explicitly cast everything. So just when it’s time to print, get a string representation of your date using str(date).

One last thing. When you tried to print the dates, you printed mylist. If you want to print a date, you must print the date objects, not their container (the list).

E.G, you want to print all the date in a list :

for date in mylist :
    print str(date)

Note that in that specific case, you can even omit str() because print will use it for you. But it should not become a habit :-)

Practical case, using your code

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22

# It's better to always use str() because :

print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22

print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects

print "This is a new day : " + str(mylist[0]) 
>>> This is a new day : 2008-11-22

Advanced date formatting

Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the strftime() method.

strftime() expects a string pattern explaining how you want to format your date.

E.G :

print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'

All the letter after a "%" represent a format for something :

  • %d is the day number
  • %m is the month number
  • %b is the month abbreviation
  • %y is the year last two digits
  • %Y is the all year

etc

Have a look at the official documentation, or McCutchen’s quick reference you can’t know them all.

Since PEP3101, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in strftime. So you can do the same as above like this:

print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'

The advantage of this form is that you can also convert other objects at the same time.
With the introduction of Formatted string literals (since Python 3.6, 2016-12-23) this can be written as

import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'

Localization

Dates can automatically adapt to the local language and culture if you use them the right way, but it’s a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)


回答 1

import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

编辑:

在Cees建议之后,我也开始使用时间:

import time
print time.strftime("%Y-%m-%d %H:%M")
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

Edit:

After Cees suggestion, I have started using time as well:

import time
print time.strftime("%Y-%m-%d %H:%M")

回答 2

date,datetime和time对象均支持strftime(format)方法,以在显式格式字符串的控制下创建表示时间的字符串。

这是格式代码及其指令和含义的列表。

    %a  Locales abbreviated weekday name.
    %A  Locales full weekday name.      
    %b  Locales abbreviated month name.     
    %B  Locales full month name.
    %c  Locales appropriate date and time representation.   
    %d  Day of the month as a decimal number [01,31].    
    %f  Microsecond as a decimal number [0,999999], zero-padded on the left
    %H  Hour (24-hour clock) as a decimal number [00,23].    
    %I  Hour (12-hour clock) as a decimal number [01,12].    
    %j  Day of the year as a decimal number [001,366].   
    %m  Month as a decimal number [01,12].   
    %M  Minute as a decimal number [00,59].      
    %p  Locales equivalent of either AM or PM.
    %S  Second as a decimal number [00,61].
    %U  Week number of the year (Sunday as the first day of the week)
    %w  Weekday as a decimal number [0(Sunday),6].   
    %W  Week number of the year (Monday as the first day of the week)
    %x  Locales appropriate date representation.    
    %X  Locales appropriate time representation.    
    %y  Year without century as a decimal number [00,99].    
    %Y  Year with century as a decimal number.   
    %z  UTC offset in the form +HHMM or -HHMM.
    %Z  Time zone name (empty string if the object is naive).    
    %%  A literal '%' character.

这就是我们可以使用Python中的datetime和time模块来做的事情

    import time
    import datetime

    print "Time in seconds since the epoch: %s" %time.time()
    print "Current date and time: ", datetime.datetime.now()
    print "Or like this: ", datetime.datetime.now().strftime("%y-%m-%d-%H-%M")


    print "Current year: ", datetime.date.today().strftime("%Y")
    print "Month of year: ", datetime.date.today().strftime("%B")
    print "Week number of the year: ", datetime.date.today().strftime("%W")
    print "Weekday of the week: ", datetime.date.today().strftime("%w")
    print "Day of year: ", datetime.date.today().strftime("%j")
    print "Day of the month : ", datetime.date.today().strftime("%d")
    print "Day of week: ", datetime.date.today().strftime("%A")

这将打印出如下内容:

    Time in seconds since the epoch:    1349271346.46
    Current date and time:              2012-10-03 15:35:46.461491
    Or like this:                       12-10-03-15-35
    Current year:                       2012
    Month of year:                      October
    Week number of the year:            40
    Weekday of the week:                3
    Day of year:                        277
    Day of the month :                  03
    Day of week:                        Wednesday

The date, datetime, and time objects all support a strftime(format) method, to create a string representing the time under the control of an explicit format string.

Here is a list of the format codes with their directive and meaning.

    %a  Locale’s abbreviated weekday name.
    %A  Locale’s full weekday name.      
    %b  Locale’s abbreviated month name.     
    %B  Locale’s full month name.
    %c  Locale’s appropriate date and time representation.   
    %d  Day of the month as a decimal number [01,31].    
    %f  Microsecond as a decimal number [0,999999], zero-padded on the left
    %H  Hour (24-hour clock) as a decimal number [00,23].    
    %I  Hour (12-hour clock) as a decimal number [01,12].    
    %j  Day of the year as a decimal number [001,366].   
    %m  Month as a decimal number [01,12].   
    %M  Minute as a decimal number [00,59].      
    %p  Locale’s equivalent of either AM or PM.
    %S  Second as a decimal number [00,61].
    %U  Week number of the year (Sunday as the first day of the week)
    %w  Weekday as a decimal number [0(Sunday),6].   
    %W  Week number of the year (Monday as the first day of the week)
    %x  Locale’s appropriate date representation.    
    %X  Locale’s appropriate time representation.    
    %y  Year without century as a decimal number [00,99].    
    %Y  Year with century as a decimal number.   
    %z  UTC offset in the form +HHMM or -HHMM.
    %Z  Time zone name (empty string if the object is naive).    
    %%  A literal '%' character.

This is what we can do with the datetime and time modules in Python

    import time
    import datetime

    print "Time in seconds since the epoch: %s" %time.time()
    print "Current date and time: ", datetime.datetime.now()
    print "Or like this: ", datetime.datetime.now().strftime("%y-%m-%d-%H-%M")


    print "Current year: ", datetime.date.today().strftime("%Y")
    print "Month of year: ", datetime.date.today().strftime("%B")
    print "Week number of the year: ", datetime.date.today().strftime("%W")
    print "Weekday of the week: ", datetime.date.today().strftime("%w")
    print "Day of year: ", datetime.date.today().strftime("%j")
    print "Day of the month : ", datetime.date.today().strftime("%d")
    print "Day of week: ", datetime.date.today().strftime("%A")

That will print out something like this:

    Time in seconds since the epoch:    1349271346.46
    Current date and time:              2012-10-03 15:35:46.461491
    Or like this:                       12-10-03-15-35
    Current year:                       2012
    Month of year:                      October
    Week number of the year:            40
    Weekday of the week:                3
    Day of year:                        277
    Day of the month :                  03
    Day of week:                        Wednesday

回答 3

使用date.strftime。格式参数在文档中进行了描述

这是您想要的:

some_date.strftime('%Y-%m-%d')

这一部分考虑了语言环境。(做这个)

some_date.strftime('%c')

Use date.strftime. The formatting arguments are described in the documentation.

This one is what you wanted:

some_date.strftime('%Y-%m-%d')

This one takes Locale into account. (do this)

some_date.strftime('%c')

回答 4

这更短:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'

This is shorter:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'

回答 5

# convert date time to regular format.

d_date = datetime.datetime.now()
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)

# some other date formats.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)

输出值

2016-10-06 01:21:34 PM
06 October 2016 01:21:34 PM
2016-10-06 13:21:34
# convert date time to regular format.

d_date = datetime.datetime.now()
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)

# some other date formats.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)

OUTPUT

2016-10-06 01:21:34 PM
06 October 2016 01:21:34 PM
2016-10-06 13:21:34

回答 6

甚至

from datetime import datetime, date

"{:%d.%m.%Y}".format(datetime.now())

出:’25 .12.2013

要么

"{} - {:%d.%m.%Y}".format("Today", datetime.now())

离开:“今天-2013年12月25日”

"{:%A}".format(date.today())

出:“星期三”

'{}__{:%Y.%m.%d__%H-%M}.log'.format(__name__, datetime.now())

出:’__main ____ 2014.06.09__16-56.log’

Or even

from datetime import datetime, date

"{:%d.%m.%Y}".format(datetime.now())

Out: ‘25.12.2013

or

"{} - {:%d.%m.%Y}".format("Today", datetime.now())

Out: ‘Today – 25.12.2013’

"{:%A}".format(date.today())

Out: ‘Wednesday’

'{}__{:%Y.%m.%d__%H-%M}.log'.format(__name__, datetime.now())

Out: ‘__main____2014.06.09__16-56.log’


回答 7

简单的答案-

datetime.date.today().isoformat()

Simple answer –

datetime.date.today().isoformat()

回答 8

格式化的字符串文字中使用特定于类型的datetime字符串格式(请参阅nk9的答案str.format()。)(自Python 3.6,2016-12-23起):

>>> import datetime
>>> f"{datetime.datetime.now():%Y-%m-%d}"
'2017-06-15'

日期/时间格式指令不会记录为部分格式字符串语法,而是在datedatetimetimestrftime()文档。它们基于1989 C标准,但自Python 3.6起包含一些ISO 8601指令。

With type-specific datetime string formatting (see nk9’s answer using str.format().) in a Formatted string literal (since Python 3.6, 2016-12-23):

>>> import datetime
>>> f"{datetime.datetime.now():%Y-%m-%d}"
'2017-06-15'

The date/time format directives are not documented as part of the Format String Syntax but rather in date, datetime, and time‘s strftime() documentation. The are based on the 1989 C Standard, but include some ISO 8601 directives since Python 3.6.


回答 9

您需要将日期时间对象转换为字符串。

以下代码为我工作:

import datetime
collection = []
dateTimeString = str(datetime.date.today())
collection.append(dateTimeString)
print collection

让我知道您是否需要更多帮助。

You need to convert the date time object to a string.

The following code worked for me:

import datetime
collection = []
dateTimeString = str(datetime.date.today())
collection.append(dateTimeString)
print collection

Let me know if you need any more help.


回答 10

你可以做:

mylist.append(str(today))

You can do:

mylist.append(str(today))

回答 11

我讨厌为了方便而导入太多模块的想法。我宁愿使用可用模块,在这种情况下也datetime不愿调用新模块time

>>> a = datetime.datetime(2015, 04, 01, 11, 23, 22)
>>> a.strftime('%Y-%m-%d %H:%M')
'2015-04-01 11:23'

I hate the idea of importing too many modules for convenience. I would rather work with available module which in this case is datetime rather than calling a new module time.

>>> a = datetime.datetime(2015, 04, 01, 11, 23, 22)
>>> a.strftime('%Y-%m-%d %H:%M')
'2015-04-01 11:23'

回答 12

考虑到您要求做一些简单的事情来做自己想做的事情,您可以:

import datetime
str(datetime.date.today())

Considering the fact you asked for something simple to do what you wanted, you could just:

import datetime
str(datetime.date.today())

回答 13

对于那些想要基于区域设置的日期而不包括时间的人,请使用:

>>> some_date.strftime('%x')
07/11/2019

For those wanting locale-based date and not including time, use:

>>> some_date.strftime('%x')
07/11/2019

回答 14

您可能想将其附加为字符串?

import datetime 
mylist = [] 
today = str(datetime.date.today())
mylist.append(today) 
print mylist

You may want to append it as a string?

import datetime 
mylist = [] 
today = str(datetime.date.today())
mylist.append(today) 
print mylist

回答 15

由于print today返回所需的内容,因此这意味着Today对象的__str__函数将返回您要查找的字符串。

所以你也可以做mylist.append(today.__str__())

Since the print today returns what you want this means that the today object’s __str__ function returns the string you are looking for.

So you can do mylist.append(today.__str__()) as well.


回答 16

您可以使用easy_date使其变得容易:

import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')

You can use easy_date to make it easy:

import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')

回答 17

我的答案免责声明-我只学习Python大约2周,所以我绝不是专家。因此,我的解释可能不是最好的,并且我可能使用了错误的术语。无论如何,就这样。

我在您的代码中注意到,在声明变量时,today = datetime.date.today()您选择使用内置函数的名称来命名变量。

当您的下一行代码mylist.append(today)附加到列表中时,它附加了整个字符串datetime.date.today()(您之前将其设置为today变量的值),而不仅仅是追加了today()

一个简单的解决方案是更改变量的名称,尽管大多数编码人员在使用datetime模块时不会使用该解决方案。

这是我尝试过的:

import datetime
mylist = []
present = datetime.date.today()
mylist.append(present)
print present

它打印yyyy-mm-dd

A quick disclaimer for my answer – I’ve only been learning Python for about 2 weeks, so I am by no means an expert; therefore, my explanation may not be the best and I may use incorrect terminology. Anyway, here it goes.

I noticed in your code that when you declared your variable today = datetime.date.today() you chose to name your variable with the name of a built-in function.

When your next line of code mylist.append(today) appended your list, it appended the entire string datetime.date.today(), which you had previously set as the value of your today variable, rather than just appending today().

A simple solution, albeit maybe not one most coders would use when working with the datetime module, is to change the name of your variable.

Here’s what I tried:

import datetime
mylist = []
present = datetime.date.today()
mylist.append(present)
print present

and it prints yyyy-mm-dd.


回答 18

这是将日期显示为(年/月/日)的方法:

from datetime import datetime
now = datetime.now()

print '%s/%s/%s' % (now.year, now.month, now.day)

Here is how to display the date as (year/month/day) :

from datetime import datetime
now = datetime.now()

print '%s/%s/%s' % (now.year, now.month, now.day)

回答 19

from datetime import date
def time-format():
  return str(date.today())
print (time-format())

如果那是您想要的,它将打印6-23-2018 :)

from datetime import date
def time-format():
  return str(date.today())
print (time-format())

this will print 6-23-2018 if that’s what you want :)


回答 20

import datetime
import time

months = ["Unknown","January","Febuary","Marchh","April","May","June","July","August","September","October","November","December"]
datetimeWrite = (time.strftime("%d-%m-%Y "))
date = time.strftime("%d")
month= time.strftime("%m")
choices = {'01': 'Jan', '02':'Feb','03':'Mar','04':'Apr','05':'May','06': 'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov','12':'Dec'}
result = choices.get(month, 'default')
year = time.strftime("%Y")
Date = date+"-"+result+"-"+year
print Date

这样,您就可以将日期格式设置为以下示例:22-Jun-2017

import datetime
import time

months = ["Unknown","January","Febuary","Marchh","April","May","June","July","August","September","October","November","December"]
datetimeWrite = (time.strftime("%d-%m-%Y "))
date = time.strftime("%d")
month= time.strftime("%m")
choices = {'01': 'Jan', '02':'Feb','03':'Mar','04':'Apr','05':'May','06': 'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov','12':'Dec'}
result = choices.get(month, 'default')
year = time.strftime("%Y")
Date = date+"-"+result+"-"+year
print Date

In this way you can get Date formatted like this example: 22-Jun-2017


回答 21

我不太了解,但是可以pandas用来获取正确格式的时间:

>>> import pandas as pd
>>> pd.to_datetime('now')
Timestamp('2018-10-07 06:03:30')
>>> print(pd.to_datetime('now'))
2018-10-07 06:03:47
>>> pd.to_datetime('now').date()
datetime.date(2018, 10, 7)
>>> print(pd.to_datetime('now').date())
2018-10-07
>>> 

和:

>>> l=[]
>>> l.append(pd.to_datetime('now').date())
>>> l
[datetime.date(2018, 10, 7)]
>>> map(str,l)
<map object at 0x0000005F67CCDF98>
>>> list(map(str,l))
['2018-10-07']

但是它存储字符串,但易于转换:

>>> l=list(map(str,l))
>>> list(map(pd.to_datetime,l))
[Timestamp('2018-10-07 00:00:00')]

I don’t fully understand but, can use pandas for getting times in right format:

>>> import pandas as pd
>>> pd.to_datetime('now')
Timestamp('2018-10-07 06:03:30')
>>> print(pd.to_datetime('now'))
2018-10-07 06:03:47
>>> pd.to_datetime('now').date()
datetime.date(2018, 10, 7)
>>> print(pd.to_datetime('now').date())
2018-10-07
>>> 

And:

>>> l=[]
>>> l.append(pd.to_datetime('now').date())
>>> l
[datetime.date(2018, 10, 7)]
>>> map(str,l)
<map object at 0x0000005F67CCDF98>
>>> list(map(str,l))
['2018-10-07']

But it’s storing strings but easy to convert:

>>> l=list(map(str,l))
>>> list(map(pd.to_datetime,l))
[Timestamp('2018-10-07 00:00:00')]

如何将日期时间转换为日期(在Python中)?

问题:如何将日期时间转换为日期(在Python中)?

如何转换datetime.datetime对象(例如,datetime.datetime.now())datetime.datePython中的对象?

How do I convert a datetime.datetime object (e.g., the return value of datetime.datetime.now()) to a datetime.date object in Python?


回答 0

使用date()方法:

datetime.datetime.now().date()

Use the date() method:

datetime.datetime.now().date()

回答 1

从文档中:

datetime.datetime.date()

返回具有相同年份,月份和日期的日期对象。

From the documentation:

datetime.datetime.date()

Return date object with same year, month and day.


回答 2

您使用的datetime.datetime.date()方法:

datetime.datetime.now().date()

显然,以上表达式可以(并且应该恕我直言:)写成:

datetime.date.today()

You use the datetime.datetime.date() method:

datetime.datetime.now().date()

Obviously, the expression above can (and should IMHO :) be written as:

datetime.date.today()

回答 3

您可以使用日期时间对象的date()方法将datetime对象转换为日期,如下所示:

<datetime_object>.date()

You can convert a datetime object to a date with the date() method of the date time object, as follows:

<datetime_object>.date()

回答 4

import time
import datetime

# use mktime to step by one day
# end - the last day, numdays - count of days to step back
def gen_dates_list(end, numdays):
  start = end - datetime.timedelta(days=numdays+1)
  end   = int(time.mktime(end.timetuple()))
  start = int(time.mktime(start.timetuple()))
  # 86400 s = 1 day
  return xrange(start, end, 86400)

# if you need reverse the list of dates
for dt in reversed(gen_dates_list(datetime.datetime.today(), 100)):
    print datetime.datetime.fromtimestamp(dt).date()
import time
import datetime

# use mktime to step by one day
# end - the last day, numdays - count of days to step back
def gen_dates_list(end, numdays):
  start = end - datetime.timedelta(days=numdays+1)
  end   = int(time.mktime(end.timetuple()))
  start = int(time.mktime(start.timetuple()))
  # 86400 s = 1 day
  return xrange(start, end, 86400)

# if you need reverse the list of dates
for dt in reversed(gen_dates_list(datetime.datetime.today(), 100)):
    print datetime.datetime.fromtimestamp(dt).date()

回答 5

您可以输入以下代码形式((今天的日期和日期和时间的名称)datetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S')

’19 -09-09 Mon 17:37:56′

并输入以下代码(用于今天):“ datetime.date.today().strftime('%y-%m-%d') 19-09-10”

对于对象: datetime.datetime.now().date() datetime.datetime.today().date() datetime.datetime.utcnow().date() datetime.datetime.today().time() datetime.datetime.utcnow().date() datetime.datetime.utcnow().time()

you could enter this code form for (today date & Names of the Day & hour) : datetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S')

’19-09-09 Mon 17:37:56′

and enter this code for (today date simply): datetime.date.today().strftime('%y-%m-%d') ’19-09-10′

for object : datetime.datetime.now().date() datetime.datetime.today().date() datetime.datetime.utcnow().date() datetime.datetime.today().time() datetime.datetime.utcnow().date() datetime.datetime.utcnow().time()


如何解析ISO 8601格式的日期?

问题:如何解析ISO 8601格式的日期?

我需要将RFC 3339字符串解析"2008-09-03T20:56:35.450686Z"为Python的datetime类型。

我已经strptime在Python标准库中找到了,但这不是很方便。

做这个的最好方式是什么?

I need to parse RFC 3339 strings like "2008-09-03T20:56:35.450686Z" into Python’s datetime type.

I have found strptime in the Python standard library, but it is not very convenient.

What is the best way to do this?


回答 0

Python-dateutil包可以解析不仅RFC 3339日期时间字符串像在的问题,还包括其他ISO 8601的日期和时间字符串不符合RFC 3339(如那些没有UTC偏移,或那些代表仅一个日期)。

>>> import dateutil.parser
>>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686Z') # RFC 3339 format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())
>>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686') # ISO 8601 extended format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.isoparse('20080903T205635.450686') # ISO 8601 basic format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.isoparse('20080903') # ISO 8601 basic format, date only
datetime.datetime(2008, 9, 3, 0, 0)

请注意,这dateutil.parser.isoparse可能比更严格的方法更严格dateutil.parser.parse,但是它们两者都是相当宽容的,并且会尝试解释您传入的字符串。如果要消除任何误读的可能性,则需要使用比这两种方法都更严格的方法功能。

Pypi名称是python-dateutil,不是dateutil(感谢code3monk3y):

pip install python-dateutil

如果您使用的是Python 3.7,请查看有关的答案datetime.datetime.fromisoformat

The python-dateutil package can parse not only RFC 3339 datetime strings like the one in the question, but also other ISO 8601 date and time strings that don’t comply with RFC 3339 (such as ones with no UTC offset, or ones that represent only a date).

>>> import dateutil.parser
>>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686Z') # RFC 3339 format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())
>>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686') # ISO 8601 extended format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.isoparse('20080903T205635.450686') # ISO 8601 basic format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.isoparse('20080903') # ISO 8601 basic format, date only
datetime.datetime(2008, 9, 3, 0, 0)

Note that dateutil.parser.isoparse is presumably stricter than the more hacky dateutil.parser.parse, but both of them are quite forgiving and will attempt to interpret the string that you pass in. If you want to eliminate the possibility of any misreads, you need to use something stricter than either of these functions.

The Pypi name is python-dateutil, not dateutil (thanks code3monk3y):

pip install python-dateutil

If you’re using Python 3.7, have a look at this answer about datetime.datetime.fromisoformat.


回答 1

Python 3.7+中的新功能


datetime标准库中引入了一个功能反转datetime.isoformat()

classmethod datetime.fromisoformat(date_string)

以和发出的格式之一返回datetime对应于的。date_stringdate.isoformat()datetime.isoformat()

具体来说,此函数支持以下格式的字符串:

YYYY-MM-DD[*HH[:MM[:SS[.mmm[mmm]]]][+HH:MM[:SS[.ffffff]]]]

在哪里*可以匹配任何单个字符。

注意:这不支持解析任意ISO 8601字符串-只能用作的反操作datetime.isoformat()

使用示例:

from datetime import datetime

date = datetime.fromisoformat('2017-01-01T12:30:59.000000')

New in Python 3.7+


The datetime standard library introduced a function for inverting datetime.isoformat().

classmethod datetime.fromisoformat(date_string):

Return a datetime corresponding to a date_string in one of the formats emitted by date.isoformat() and datetime.isoformat().

Specifically, this function supports strings in the format(s):

YYYY-MM-DD[*HH[:MM[:SS[.mmm[mmm]]]][+HH:MM[:SS[.ffffff]]]]

where * can match any single character.

Caution: This does not support parsing arbitrary ISO 8601 strings – it is only intended as the inverse operation of datetime.isoformat().

Example of use:

from datetime import datetime

date = datetime.fromisoformat('2017-01-01T12:30:59.000000')

回答 2

请注意,在Python 2.6+和Py3K中,%f字符捕获微秒。

>>> datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")

在这里查看问题

Note in Python 2.6+ and Py3K, the %f character catches microseconds.

>>> datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")

See issue here


回答 3

这里有几个答案 建议使用解析时区的RFC 3339或ISO 8601日期时间,就像问题中展示的那样: datetime.datetime.strptime

2008-09-03T20:56:35.450686Z

这是一个坏主意。

假设您要支持完整的RFC 3339格式,包括对非零的UTC偏移量的支持,那么这些答案所建议的代码将不起作用。事实上,它不能工作,因为解析RFC 3339语法使用strptime是不可能的。Python的datetime模块使用的格式字符串无法描述RFC 3339语法。

问题是UTC偏移量。在RFC 3339互联网日期/时间格式要求每个日期时间包括UTC偏移,并且这些偏移可以是Z(以下简称“祖鲁时间”),或在+HH:MM-HH:MM格式,如+05:00-10:30

因此,这些都是有效的RFC 3339日期时间:

  • 2008-09-03T20:56:35.450686Z
  • 2008-09-03T20:56:35.450686+05:00
  • 2008-09-03T20:56:35.450686-10:30

可惜的是,所使用的格式字符串通过strptimestrftime没有指令,对应于RFC 3339格式的UTC偏移。可以在https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior中找到它们支持的指令的完整列表,并且列表中唯一包含的UTC偏移量指令是%z

%z

UTC偏移量,格式为+ HHMM或-HHMM(如果对象是天真对象,则为空字符串)。

例如:(空),+ 0000,-0400,+ 1030

这与RFC 3339偏移量的格式不匹配,实际上,如果我们尝试%z在格式字符串中使用并解析RFC 3339日期,则将失败:

>>> from datetime import datetime
>>> datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%f%z")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
>>> datetime.strptime("2008-09-03T20:56:35.450686+05:00", "%Y-%m-%dT%H:%M:%S.%f%z")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686+05:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

(实际上,以上内容就是您在Python 3中看到的。在Python 2中,我们失败的原因更为简单,这是因为strptime%z在Python 2根本没有实现该指令。)

推荐使用以下strptime所有方法的多个答案都可以通过Z在其格式字符串中包含一个字面量来解决此问题,该字面量与Z问题质询者的示例datetime字符串中的匹配(并丢弃它,从而生成datetime没有时区的对象):

>>> datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)

由于这会丢弃原始datetime字符串中包含的时区信息,因此我们是否应该甚至将此结果都视为正确还值得怀疑。但更重要的是,由于此方法涉及将特定的UTC偏移量硬编码到格式字符串中,因此它将在尝试解析具有不同UTC偏移量的任何RFC 3339日期时间时将阻塞:

>>> datetime.strptime("2008-09-03T20:56:35.450686+05:00", "%Y-%m-%dT%H:%M:%S.%fZ")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686+05:00' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

除非您确定只需要在Zulu时间中支持RFC 3339日期时间,而不是具有其他时区偏移量的日期时间,请不要使用strptime。请改用此处答案中描述的许多其他方法之一。

Several answers here suggest using datetime.datetime.strptime to parse RFC 3339 or ISO 8601 datetimes with timezones, like the one exhibited in the question:

2008-09-03T20:56:35.450686Z

This is a bad idea.

Assuming that you want to support the full RFC 3339 format, including support for UTC offsets other than zero, then the code these answers suggest does not work. Indeed, it cannot work, because parsing RFC 3339 syntax using strptime is impossible. The format strings used by Python’s datetime module are incapable of describing RFC 3339 syntax.

The problem is UTC offsets. The RFC 3339 Internet Date/Time Format requires that every date-time includes a UTC offset, and that those offsets can either be Z (short for “Zulu time”) or in +HH:MM or -HH:MM format, like +05:00 or -10:30.

Consequently, these are all valid RFC 3339 datetimes:

  • 2008-09-03T20:56:35.450686Z
  • 2008-09-03T20:56:35.450686+05:00
  • 2008-09-03T20:56:35.450686-10:30

Alas, the format strings used by strptime and strftime have no directive that corresponds to UTC offsets in RFC 3339 format. A complete list of the directives they support can be found at https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior, and the only UTC offset directive included in the list is %z:

%z

UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).

Example: (empty), +0000, -0400, +1030

This doesn’t match the format of an RFC 3339 offset, and indeed if we try to use %z in the format string and parse an RFC 3339 date, we’ll fail:

>>> from datetime import datetime
>>> datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%f%z")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
>>> datetime.strptime("2008-09-03T20:56:35.450686+05:00", "%Y-%m-%dT%H:%M:%S.%f%z")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686+05:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

(Actually, the above is just what you’ll see in Python 3. In Python 2 we’ll fail for an even simpler reason, which is that strptime does not implement the %z directive at all in Python 2.)

The multiple answers here that recommend strptime all work around this by including a literal Z in their format string, which matches the Z from the question asker’s example datetime string (and discards it, producing a datetime object without a timezone):

>>> datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)

Since this discards timezone information that was included in the original datetime string, it’s questionable whether we should regard even this result as correct. But more importantly, because this approach involves hard-coding a particular UTC offset into the format string, it will choke the moment it tries to parse any RFC 3339 datetime with a different UTC offset:

>>> datetime.strptime("2008-09-03T20:56:35.450686+05:00", "%Y-%m-%dT%H:%M:%S.%fZ")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686+05:00' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

Unless you’re certain that you only need to support RFC 3339 datetimes in Zulu time, and not ones with other timezone offsets, don’t use strptime. Use one of the many other approaches described in answers here instead.


回答 4

尝试使用iso8601模块;它正是这样做的。

python.org Wiki 上的WorkingWithTime页面上提到了其他几个选项。

Try the iso8601 module; it does exactly this.

There are several other options mentioned on the WorkingWithTime page on the python.org wiki.


回答 5

导入时间,日期时间
s =“ 2008-09-03T20:56:35.450686Z”
d = datetime.datetime(* map(int,re.split('[^ \ d]',s)[:-1]))
import re,datetime
s="2008-09-03T20:56:35.450686Z"
d=datetime.datetime(*map(int, re.split('[^\d]', s)[:-1]))

回答 6

您得到的确切错误是什么?像下面吗?

>>> datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z")
ValueError: time data did not match format:  data=2008-08-12T12:20:30.656234Z  fmt=%Y-%m-%dT%H:%M:%S.Z

如果是,则可以在“。”上分割输入字符串,然后将微秒添加到您获得的日期时间。

尝试这个:

>>> def gt(dt_str):
        dt, _, us= dt_str.partition(".")
        dt= datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
        us= int(us.rstrip("Z"), 10)
        return dt + datetime.timedelta(microseconds=us)

>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)

What is the exact error you get? Is it like the following?

>>> datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z")
ValueError: time data did not match format:  data=2008-08-12T12:20:30.656234Z  fmt=%Y-%m-%dT%H:%M:%S.Z

If yes, you can split your input string on “.”, and then add the microseconds to the datetime you got.

Try this:

>>> def gt(dt_str):
        dt, _, us= dt_str.partition(".")
        dt= datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
        us= int(us.rstrip("Z"), 10)
        return dt + datetime.timedelta(microseconds=us)

>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)

回答 7

从Python 3.7开始,strptime在UTC偏移量()中支持冒号分隔符。因此,您可以使用:

import datetime
datetime.datetime.strptime('2018-01-31T09:24:31.488670+00:00', '%Y-%m-%dT%H:%M:%S.%f%z')

编辑:

正如Martijn所指出的那样,如果您使用isoformat()创建了datetime对象,则只需使用datetime.fromisoformat()

Starting from Python 3.7, strptime supports colon delimiters in UTC offsets (source). So you can then use:

import datetime
datetime.datetime.strptime('2018-01-31T09:24:31.488670+00:00', '%Y-%m-%dT%H:%M:%S.%f%z')

EDIT:

As pointed out by Martijn, if you created the datetime object using isoformat(), you can simply use datetime.fromisoformat()


回答 8

如今,Arrow还可以用作第三方解决方案:

>>> import arrow
>>> date = arrow.get("2008-09-03T20:56:35.450686Z")
>>> date.datetime
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())

In these days, Arrow also can be used as a third-party solution:

>>> import arrow
>>> date = arrow.get("2008-09-03T20:56:35.450686Z")
>>> date.datetime
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())

回答 9

只需使用python-dateutil模块:

>>> import dateutil.parser as dp
>>> t = '1984-06-02T19:05:00.000Z'
>>> parsed_t = dp.parse(t)
>>> print(parsed_t)
datetime.datetime(1984, 6, 2, 19, 5, tzinfo=tzutc())

文献资料

Just use the python-dateutil module:

>>> import dateutil.parser as dp
>>> t = '1984-06-02T19:05:00.000Z'
>>> parsed_t = dp.parse(t)
>>> print(parsed_t)
datetime.datetime(1984, 6, 2, 19, 5, tzinfo=tzutc())

Documentation


回答 10

如果您不想使用dateutil,可以尝试以下功能:

def from_utc(utcTime,fmt="%Y-%m-%dT%H:%M:%S.%fZ"):
    """
    Convert UTC time string to time.struct_time
    """
    # change datetime.datetime to time, return time.struct_time type
    return datetime.datetime.strptime(utcTime, fmt)

测试:

from_utc("2007-03-04T21:08:12.123Z")

结果:

datetime.datetime(2007, 3, 4, 21, 8, 12, 123000)

If you don’t want to use dateutil, you can try this function:

def from_utc(utcTime,fmt="%Y-%m-%dT%H:%M:%S.%fZ"):
    """
    Convert UTC time string to time.struct_time
    """
    # change datetime.datetime to time, return time.struct_time type
    return datetime.datetime.strptime(utcTime, fmt)

Test:

from_utc("2007-03-04T21:08:12.123Z")

Result:

datetime.datetime(2007, 3, 4, 21, 8, 12, 123000)

回答 11

如果使用Django,它将提供dateparse模块,该模块接受一堆类似于ISO格式的格式,包括时区。

如果您不使用Django,并且不想使用此处提到的其他库之一,则可以将dateparse的Django源代码修改为您的项目。

If you are working with Django, it provides the dateparse module that accepts a bunch of formats similar to ISO format, including the time zone.

If you are not using Django and you don’t want to use one of the other libraries mentioned here, you could probably adapt the Django source code for dateparse to your project.


回答 12

我发现ciso8601是解析ISO 8601时间戳的最快方法。顾名思义,它是用C实现的。

import ciso8601
ciso8601.parse_datetime('2014-01-09T21:48:00.921000+05:30')

GitHub库自述相对于其他答案中列出的所有其他库显示了它们的> 10倍加速。

我的个人项目涉及很多ISO 8601解析。能够切换通话并加快10倍速度真是太好了。:)

编辑:我从此成为ciso8601的维护者。现在比以往更快!

I have found ciso8601 to be the fastest way to parse ISO 8601 timestamps. As the name suggests, it is implemented in C.

import ciso8601
ciso8601.parse_datetime('2014-01-09T21:48:00.921000+05:30')

The GitHub Repo README shows their >10x speedup versus all of the other libraries listed in the other answers.

My personal project involved a lot of ISO 8601 parsing. It was nice to be able to just switch the call and go 10x faster. :)

Edit: I have since become a maintainer of ciso8601. It’s now faster than ever!


回答 13

这适用于从Python 3.2开始的stdlib(假设所有时间戳均为UTC):

from datetime import datetime, timezone, timedelta
datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ").replace(
    tzinfo=timezone(timedelta(0)))

例如,

>>> datetime.utcnow().replace(tzinfo=timezone(timedelta(0)))
... datetime.datetime(2015, 3, 11, 6, 2, 47, 879129, tzinfo=datetime.timezone.utc)

This works for stdlib on Python 3.2 onwards (assuming all the timestamps are UTC):

from datetime import datetime, timezone, timedelta
datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ").replace(
    tzinfo=timezone(timedelta(0)))

For example,

>>> datetime.utcnow().replace(tzinfo=timezone(timedelta(0)))
... datetime.datetime(2015, 3, 11, 6, 2, 47, 879129, tzinfo=datetime.timezone.utc)

回答 14

我是iso8601 utils的作者。可以在GitHubPyPI 上找到它。这是解析示例的方法:

>>> from iso8601utils import parsers
>>> parsers.datetime('2008-09-03T20:56:35.450686Z')
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)

I’m the author of iso8601 utils. It can be found on GitHub or on PyPI. Here’s how you can parse your example:

>>> from iso8601utils import parsers
>>> parsers.datetime('2008-09-03T20:56:35.450686Z')
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)

回答 15

datetime.datetime在不安装第三方模块的情况下,在所有受支持的Python版本中将类似于ISO 8601的日期字符串转换为UNIX时间戳或对象的一种直接方法是使用SQLite日期解析器

#!/usr/bin/env python
from __future__ import with_statement, division, print_function
import sqlite3
import datetime

testtimes = [
    "2016-08-25T16:01:26.123456Z",
    "2016-08-25T16:01:29",
]
db = sqlite3.connect(":memory:")
c = db.cursor()
for timestring in testtimes:
    c.execute("SELECT strftime('%s', ?)", (timestring,))
    converted = c.fetchone()[0]
    print("%s is %s after epoch" % (timestring, converted))
    dt = datetime.datetime.fromtimestamp(int(converted))
    print("datetime is %s" % dt)

输出:

2016-08-25T16:01:26.123456Z is 1472140886 after epoch
datetime is 2016-08-25 12:01:26
2016-08-25T16:01:29 is 1472140889 after epoch
datetime is 2016-08-25 12:01:29

One straightforward way to convert an ISO 8601-like date string to a UNIX timestamp or datetime.datetime object in all supported Python versions without installing third-party modules is to use the date parser of SQLite.

#!/usr/bin/env python
from __future__ import with_statement, division, print_function
import sqlite3
import datetime

testtimes = [
    "2016-08-25T16:01:26.123456Z",
    "2016-08-25T16:01:29",
]
db = sqlite3.connect(":memory:")
c = db.cursor()
for timestring in testtimes:
    c.execute("SELECT strftime('%s', ?)", (timestring,))
    converted = c.fetchone()[0]
    print("%s is %s after epoch" % (timestring, converted))
    dt = datetime.datetime.fromtimestamp(int(converted))
    print("datetime is %s" % dt)

Output:

2016-08-25T16:01:26.123456Z is 1472140886 after epoch
datetime is 2016-08-25 12:01:26
2016-08-25T16:01:29 is 1472140889 after epoch
datetime is 2016-08-25 12:01:29

回答 16

我已经为ISO 8601标准编写了一个解析器,并将其放在GitHub上:https : //github.com/boxed/iso8601。此实现支持规范中的所有内容,但持续时间,间隔,周期性间隔和日期不在Python datetime模块支持的日期范围内。

测试包括在内!:P

I’ve coded up a parser for the ISO 8601 standard and put it on GitHub: https://github.com/boxed/iso8601. This implementation supports everything in the specification except for durations, intervals, periodic intervals, and dates outside the supported date range of Python’s datetime module.

Tests are included! :P


回答 17

Django的parse_datetime()函数支持带有UTC偏移量的日期:

parse_datetime('2016-08-09T15:12:03.65478Z') =
datetime.datetime(2016, 8, 9, 15, 12, 3, 654780, tzinfo=<UTC>)

因此,它可用于解析整个项目中字段中的ISO 8601日期:

from django.utils import formats
from django.forms.fields import DateTimeField
from django.utils.dateparse import parse_datetime

class DateTimeFieldFixed(DateTimeField):
    def strptime(self, value, format):
        if format == 'iso-8601':
            return parse_datetime(value)
        return super().strptime(value, format)

DateTimeField.strptime = DateTimeFieldFixed.strptime
formats.ISO_INPUT_FORMATS['DATETIME_INPUT_FORMATS'].insert(0, 'iso-8601')

Django’s parse_datetime() function supports dates with UTC offsets:

parse_datetime('2016-08-09T15:12:03.65478Z') =
datetime.datetime(2016, 8, 9, 15, 12, 3, 654780, tzinfo=<UTC>)

So it could be used for parsing ISO 8601 dates in fields within entire project:

from django.utils import formats
from django.forms.fields import DateTimeField
from django.utils.dateparse import parse_datetime

class DateTimeFieldFixed(DateTimeField):
    def strptime(self, value, format):
        if format == 'iso-8601':
            return parse_datetime(value)
        return super().strptime(value, format)

DateTimeField.strptime = DateTimeFieldFixed.strptime
formats.ISO_INPUT_FORMATS['DATETIME_INPUT_FORMATS'].insert(0, 'iso-8601')

回答 18

因为ISO 8601允许出现许多可选的冒号和破折号,基本上是这样CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]。如果要使用strptime,则需要先删除这些变化。

目标是生成utc datetime对象。


如果您只想使用带有Z后缀的UTC的基本情况,例如2016-06-29T19:36:29.3453Z

datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")


如果您想处理时区偏移 2016-06-29T19:36:29.3453-0400,请2008-09-03T20:56:35.450686+05:00使用以下方法。这些将所有变体转换成没有变量定界符的东西,例如 20080903T205635.450686+0500使其更一致/更容易解析。

import re
# this regex removes all colons and all 
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )


如果您的系统不支持%zstrptime指令(您看到类似的信息ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z'),那么您需要手动将时间与Z(UTC)相抵消。注意%z在python版本<3中可能无法在您的系统上运行,因为它取决于c库支持,该支持因系统/ python构建类型(即Jython,Cython等)而异。

import re
import datetime

# this regex removes all colons and all 
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)

# split on the offset to remove it. use a capture group to keep the delimiter
split_timestamp = re.split(r"[+|-]",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
    sign = split_timestamp[1]
    offset = split_timestamp[2]
else:
    sign = None
    offset = None

# generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
    # create timedelta based on offset
    offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))
    # offset datetime with timedelta
    output_datetime = output_datetime + offset_delta

Because ISO 8601 allows many variations of optional colons and dashes being present, basically CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]. If you want to use strptime, you need to strip out those variations first.

The goal is to generate a utc datetime object.


If you just want a basic case that work for UTC with the Z suffix like 2016-06-29T19:36:29.3453Z:
datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")


If you want to handle timezone offsets like 2016-06-29T19:36:29.3453-0400 or 2008-09-03T20:56:35.450686+05:00 use the following. These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500 making it more consistent/easier to parse.
import re
# this regex removes all colons and all 
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )


If your system does not support the %z strptime directive (you see something like ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z') then you need to manually offset the time from Z (UTC). Note %z may not work on your system in python versions < 3 as it depended on the c library support which varies across system/python build type (i.e. Jython, Cython, etc.).
import re
import datetime

# this regex removes all colons and all 
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)

# split on the offset to remove it. use a capture group to keep the delimiter
split_timestamp = re.split(r"[+|-]",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
    sign = split_timestamp[1]
    offset = split_timestamp[2]
else:
    sign = None
    offset = None

# generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
    # create timedelta based on offset
    offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))
    # offset datetime with timedelta
    output_datetime = output_datetime + offset_delta

回答 19

对于适用于2.X标准库的内容,请尝试:

calendar.timegm(time.strptime(date.split(".")[0]+"UTC", "%Y-%m-%dT%H:%M:%S%Z"))

calendar.timegm是time.mktime缺少的gm版本。

For something that works with the 2.X standard library try:

calendar.timegm(time.strptime(date.split(".")[0]+"UTC", "%Y-%m-%dT%H:%M:%S%Z"))

calendar.timegm is the missing gm version of time.mktime.


回答 20

如果解析无效的日期字符串,则python-dateutil将引发异常,因此您可能想捕获该异常。

from dateutil import parser
ds = '2012-60-31'
try:
  dt = parser.parse(ds)
except ValueError, e:
  print '"%s" is an invalid date' % ds

The python-dateutil will throw an exception if parsing invalid date strings, so you may want to catch the exception.

from dateutil import parser
ds = '2012-60-31'
try:
  dt = parser.parse(ds)
except ValueError, e:
  print '"%s" is an invalid date' % ds

回答 21

如今,流行的“请求:HTTP for Humans™”软件包的作者发表了《Maya:Datetimes for Humans™》

>>> import maya
>>> str = '2008-09-03T20:56:35.450686Z'
>>> maya.MayaDT.from_rfc3339(str).datetime()
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=<UTC>)

Nowadays there’s Maya: Datetimes for Humans™, from the author of the popular Requests: HTTP for Humans™ package:

>>> import maya
>>> str = '2008-09-03T20:56:35.450686Z'
>>> maya.MayaDT.from_rfc3339(str).datetime()
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=<UTC>)

回答 22

对ISO-8601使用专门的解析器的另一种方法是使用dateutil解析器的isoparse函数:

from dateutil import parser

date = parser.isoparse("2008-09-03T20:56:35.450686+01:00")
print(date)

输出:

2008-09-03 20:56:35.450686+01:00

标准Python函数datetime.fromisoformat文档中也提到了此函数

第三方软件包dateutil中提供了功能更全的ISO 8601解析器dateutil.parser.isoparse。

An another way is to use specialized parser for ISO-8601 is to use isoparse function of dateutil parser:

from dateutil import parser

date = parser.isoparse("2008-09-03T20:56:35.450686+01:00")
print(date)

Output:

2008-09-03 20:56:35.450686+01:00

This function is also mentioned in the documentation for the standard Python function datetime.fromisoformat:

A more full-featured ISO 8601 parser, dateutil.parser.isoparse is available in the third-party package dateutil.


回答 23

多亏了马克·阿默里(Mark Amery)的出色回答,我设计了函数来说明所有可能的日期时间ISO格式:

class FixedOffset(tzinfo):
    """Fixed offset in minutes: `time = utc_time + utc_offset`."""
    def __init__(self, offset):
        self.__offset = timedelta(minutes=offset)
        hours, minutes = divmod(offset, 60)
        #NOTE: the last part is to remind about deprecated POSIX GMT+h timezones
        #  that have the opposite sign in the name;
        #  the corresponding numeric value is not used e.g., no minutes
        self.__name = '<%+03d%02d>%+d' % (hours, minutes, -hours)
    def utcoffset(self, dt=None):
        return self.__offset
    def tzname(self, dt=None):
        return self.__name
    def dst(self, dt=None):
        return timedelta(0)
    def __repr__(self):
        return 'FixedOffset(%d)' % (self.utcoffset().total_seconds() / 60)
    def __getinitargs__(self):
        return (self.__offset.total_seconds()/60,)

def parse_isoformat_datetime(isodatetime):
    try:
        return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S.%f')
    except ValueError:
        pass
    try:
        return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S')
    except ValueError:
        pass
    pat = r'(.*?[+-]\d{2}):(\d{2})'
    temp = re.sub(pat, r'\1\2', isodatetime)
    naive_date_str = temp[:-5]
    offset_str = temp[-5:]
    naive_dt = datetime.strptime(naive_date_str, '%Y-%m-%dT%H:%M:%S.%f')
    offset = int(offset_str[-4:-2])*60 + int(offset_str[-2:])
    if offset_str[0] == "-":
        offset = -offset
    return naive_dt.replace(tzinfo=FixedOffset(offset))

Thanks to great Mark Amery’s answer I devised function to account for all possible ISO formats of datetime:

class FixedOffset(tzinfo):
    """Fixed offset in minutes: `time = utc_time + utc_offset`."""
    def __init__(self, offset):
        self.__offset = timedelta(minutes=offset)
        hours, minutes = divmod(offset, 60)
        #NOTE: the last part is to remind about deprecated POSIX GMT+h timezones
        #  that have the opposite sign in the name;
        #  the corresponding numeric value is not used e.g., no minutes
        self.__name = '<%+03d%02d>%+d' % (hours, minutes, -hours)
    def utcoffset(self, dt=None):
        return self.__offset
    def tzname(self, dt=None):
        return self.__name
    def dst(self, dt=None):
        return timedelta(0)
    def __repr__(self):
        return 'FixedOffset(%d)' % (self.utcoffset().total_seconds() / 60)
    def __getinitargs__(self):
        return (self.__offset.total_seconds()/60,)

def parse_isoformat_datetime(isodatetime):
    try:
        return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S.%f')
    except ValueError:
        pass
    try:
        return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S')
    except ValueError:
        pass
    pat = r'(.*?[+-]\d{2}):(\d{2})'
    temp = re.sub(pat, r'\1\2', isodatetime)
    naive_date_str = temp[:-5]
    offset_str = temp[-5:]
    naive_dt = datetime.strptime(naive_date_str, '%Y-%m-%dT%H:%M:%S.%f')
    offset = int(offset_str[-4:-2])*60 + int(offset_str[-2:])
    if offset_str[0] == "-":
        offset = -offset
    return naive_dt.replace(tzinfo=FixedOffset(offset))

回答 24

def parseISO8601DateTime(datetimeStr):
    import time
    from datetime import datetime, timedelta

    def log_date_string(when):
        gmt = time.gmtime(when)
        if time.daylight and gmt[8]:
            tz = time.altzone
        else:
            tz = time.timezone
        if tz > 0:
            neg = 1
        else:
            neg = 0
            tz = -tz
        h, rem = divmod(tz, 3600)
        m, rem = divmod(rem, 60)
        if neg:
            offset = '-%02d%02d' % (h, m)
        else:
            offset = '+%02d%02d' % (h, m)

        return time.strftime('%d/%b/%Y:%H:%M:%S ', gmt) + offset

    dt = datetime.strptime(datetimeStr, '%Y-%m-%dT%H:%M:%S.%fZ')
    timestamp = dt.timestamp()
    return dt + timedelta(hours=dt.hour-time.gmtime(timestamp).tm_hour)

请注意,如果字符串不以结尾Z,我们应该使用进行解析%z

def parseISO8601DateTime(datetimeStr):
    import time
    from datetime import datetime, timedelta

    def log_date_string(when):
        gmt = time.gmtime(when)
        if time.daylight and gmt[8]:
            tz = time.altzone
        else:
            tz = time.timezone
        if tz > 0:
            neg = 1
        else:
            neg = 0
            tz = -tz
        h, rem = divmod(tz, 3600)
        m, rem = divmod(rem, 60)
        if neg:
            offset = '-%02d%02d' % (h, m)
        else:
            offset = '+%02d%02d' % (h, m)

        return time.strftime('%d/%b/%Y:%H:%M:%S ', gmt) + offset

    dt = datetime.strptime(datetimeStr, '%Y-%m-%dT%H:%M:%S.%fZ')
    timestamp = dt.timestamp()
    return dt + timedelta(hours=dt.hour-time.gmtime(timestamp).tm_hour)

Note that we should look if the string doesn’t ends with Z, we could parse using %z.


回答 25

最初我尝试使用:

from operator import neg, pos
from time import strptime, mktime
from datetime import datetime, tzinfo, timedelta

class MyUTCOffsetTimezone(tzinfo):
    @staticmethod
    def with_offset(offset_no_signal, signal):  # type: (str, str) -> MyUTCOffsetTimezone
        return MyUTCOffsetTimezone((pos if signal == '+' else neg)(
            (datetime.strptime(offset_no_signal, '%H:%M') - datetime(1900, 1, 1))
          .total_seconds()))

    def __init__(self, offset, name=None):
        self.offset = timedelta(seconds=offset)
        self.name = name or self.__class__.__name__

    def utcoffset(self, dt):
        return self.offset

    def tzname(self, dt):
        return self.name

    def dst(self, dt):
        return timedelta(0)


def to_datetime_tz(dt):  # type: (str) -> datetime
    fmt = '%Y-%m-%dT%H:%M:%S.%f'
    if dt[-6] in frozenset(('+', '-')):
        dt, sign, offset = strptime(dt[:-6], fmt), dt[-6], dt[-5:]
        return datetime.fromtimestamp(mktime(dt),
                                      tz=MyUTCOffsetTimezone.with_offset(offset, sign))
    elif dt[-1] == 'Z':
        return datetime.strptime(dt, fmt + 'Z')
    return datetime.strptime(dt, fmt)

但这不适用于负时区。但是我在Python 3.7.3中工作得很好:

from datetime import datetime


def to_datetime_tz(dt):  # type: (str) -> datetime
    fmt = '%Y-%m-%dT%H:%M:%S.%f'
    if dt[-6] in frozenset(('+', '-')):
        return datetime.strptime(dt, fmt + '%z')
    elif dt[-1] == 'Z':
        return datetime.strptime(dt, fmt + 'Z')
    return datetime.strptime(dt, fmt)

在某些测试中,请注意输出仅相差微秒。在我的机器上达到6位精度,但是YMMV:

for dt_in, dt_out in (
        ('2019-03-11T08:00:00.000Z', '2019-03-11T08:00:00'),
        ('2019-03-11T08:00:00.000+11:00', '2019-03-11T08:00:00+11:00'),
        ('2019-03-11T08:00:00.000-11:00', '2019-03-11T08:00:00-11:00')
    ):
    isoformat = to_datetime_tz(dt_in).isoformat()
    assert isoformat == dt_out, '{} != {}'.format(isoformat, dt_out)

Initially I tried with:

from operator import neg, pos
from time import strptime, mktime
from datetime import datetime, tzinfo, timedelta

class MyUTCOffsetTimezone(tzinfo):
    @staticmethod
    def with_offset(offset_no_signal, signal):  # type: (str, str) -> MyUTCOffsetTimezone
        return MyUTCOffsetTimezone((pos if signal == '+' else neg)(
            (datetime.strptime(offset_no_signal, '%H:%M') - datetime(1900, 1, 1))
          .total_seconds()))

    def __init__(self, offset, name=None):
        self.offset = timedelta(seconds=offset)
        self.name = name or self.__class__.__name__

    def utcoffset(self, dt):
        return self.offset

    def tzname(self, dt):
        return self.name

    def dst(self, dt):
        return timedelta(0)


def to_datetime_tz(dt):  # type: (str) -> datetime
    fmt = '%Y-%m-%dT%H:%M:%S.%f'
    if dt[-6] in frozenset(('+', '-')):
        dt, sign, offset = strptime(dt[:-6], fmt), dt[-6], dt[-5:]
        return datetime.fromtimestamp(mktime(dt),
                                      tz=MyUTCOffsetTimezone.with_offset(offset, sign))
    elif dt[-1] == 'Z':
        return datetime.strptime(dt, fmt + 'Z')
    return datetime.strptime(dt, fmt)

But that didn’t work on negative timezones. This however I got working fine, in Python 3.7.3:

from datetime import datetime


def to_datetime_tz(dt):  # type: (str) -> datetime
    fmt = '%Y-%m-%dT%H:%M:%S.%f'
    if dt[-6] in frozenset(('+', '-')):
        return datetime.strptime(dt, fmt + '%z')
    elif dt[-1] == 'Z':
        return datetime.strptime(dt, fmt + 'Z')
    return datetime.strptime(dt, fmt)

Some tests, note that the out only differs by precision of microseconds. Got to 6 digits of precision on my machine, but YMMV:

for dt_in, dt_out in (
        ('2019-03-11T08:00:00.000Z', '2019-03-11T08:00:00'),
        ('2019-03-11T08:00:00.000+11:00', '2019-03-11T08:00:00+11:00'),
        ('2019-03-11T08:00:00.000-11:00', '2019-03-11T08:00:00-11:00')
    ):
    isoformat = to_datetime_tz(dt_in).isoformat()
    assert isoformat == dt_out, '{} != {}'.format(isoformat, dt_out)

将字符串转换为日期时间

问题:将字符串转换为日期时间

我有大量的日期时间列表,例如字符串:

Jun 1 2005  1:33PM
Aug 28 1999 12:00AM

我将把它们推回到数据库中正确的日期时间字段中,因此我需要将它们魔术化为实际的日期时间对象。

这是通过Django的ORM进行的,因此我无法使用SQL进行插入时的转换。

I’ve got a huge list of date-times like this as strings:

Jun 1 2005  1:33PM
Aug 28 1999 12:00AM

I’m going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.

This is going through Django’s ORM so I can’t use SQL to do the conversion on insert.


回答 0

datetime.strptime是将字符串解析为日期时间的主要例程。它可以处理各种格式,格式由您为其指定的格式字符串确定:

from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

生成的datetime对象是时区未使用的。

链接:

笔记:

  • strptime =“字符串解析时间”
  • strftime =“字符串格式时间”
  • 今天大声发音,您将在6个月内无需再次搜索。

datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:

from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

The resulting datetime object is timezone-naive.

Links:

Notes:

  • strptime = “string parse time”
  • strftime = “string format time”
  • Pronounce it out loud today & you won’t have to search for it again in 6 months.

回答 1

使用第三方dateutil库:

from dateutil import parser
parser.parse("Aug 28 1999 12:00AM")  # datetime.datetime(1999, 8, 28, 0, 0)

它可以处理大多数日期格式,包括您需要解析的格式。它比strptime大多数时候都可以猜测正确的格式要方便得多。

这对于编写测试非常有用,在测试中,可读性比性能更重要。

您可以使用以下方法安装它:

pip install python-dateutil

Use the third party dateutil library:

from dateutil import parser
parser.parse("Aug 28 1999 12:00AM")  # datetime.datetime(1999, 8, 28, 0, 0)

It can handle most date formats, including the one you need to parse. It’s more convenient than strptime as it can guess the correct format most of the time.

It’s very useful for writing tests, where readability is more important than performance.

You can install it with:

pip install python-dateutil

回答 2

时间模块中strptime。它与strftime相反。

$ python
>>> import time
>>> my_time = time.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
time.struct_time(tm_year=2005, tm_mon=6, tm_mday=1,
                 tm_hour=13, tm_min=33, tm_sec=0,
                 tm_wday=2, tm_yday=152, tm_isdst=-1)

timestamp = time.mktime(my_time)
# convert time object to datetime
from datetime import datetime
my_datetime = datetime.fromtimestamp(timestamp)
# convert time object to date
from datetime import date
my_date = date.fromtimestamp(timestamp)

Check out strptime in the time module. It is the inverse of strftime.

$ python
>>> import time
>>> my_time = time.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
time.struct_time(tm_year=2005, tm_mon=6, tm_mday=1,
                 tm_hour=13, tm_min=33, tm_sec=0,
                 tm_wday=2, tm_yday=152, tm_isdst=-1)

timestamp = time.mktime(my_time)
# convert time object to datetime
from datetime import datetime
my_datetime = datetime.fromtimestamp(timestamp)
# convert time object to date
from datetime import date
my_date = date.fromtimestamp(timestamp)

回答 3

我整理了一个可以转换一些真正简洁的表达式的项目。查看时间字符串

以下是一些示例:

pip install timestring
>>> import timestring
>>> timestring.Date('monday, aug 15th 2015 at 8:40 pm')
<timestring.Date 2015-08-15 20:40:00 4491909392>
>>> timestring.Date('monday, aug 15th 2015 at 8:40 pm').date
datetime.datetime(2015, 8, 15, 20, 40)
>>> timestring.Range('next week')
<timestring.Range From 03/10/14 00:00:00 to 03/03/14 00:00:00 4496004880>
>>> (timestring.Range('next week').start.date, timestring.Range('next week').end.date)
(datetime.datetime(2014, 3, 10, 0, 0), datetime.datetime(2014, 3, 14, 0, 0))

I have put together a project that can convert some really neat expressions. Check out timestring.

Here are some examples below:

pip install timestring
>>> import timestring
>>> timestring.Date('monday, aug 15th 2015 at 8:40 pm')
<timestring.Date 2015-08-15 20:40:00 4491909392>
>>> timestring.Date('monday, aug 15th 2015 at 8:40 pm').date
datetime.datetime(2015, 8, 15, 20, 40)
>>> timestring.Range('next week')
<timestring.Range From 03/10/14 00:00:00 to 03/03/14 00:00:00 4496004880>
>>> (timestring.Range('next week').start.date, timestring.Range('next week').end.date)
(datetime.datetime(2014, 3, 10, 0, 0), datetime.datetime(2014, 3, 14, 0, 0))

回答 4

记住这一点,您无需再次对日期时间转换感到困惑。

日期时间对象的字符串= strptime

datetime对象为其他格式= strftime

Jun 1 2005 1:33PM

等于

%b %d %Y %I:%M%p

%b月作为语言环境的缩写名称(六月)

%d月中的一天,以零填充的十进制数字(1)

%Y以世纪为十进制数字的年份(2015)

%I小时(12小时制),为零填充的十进制数字(01)

%M分钟,为零填充的十进制数字(33)

等同于AM或PM(PM)的%p语言环境

所以你需要strptime即转换string

>>> dates = []
>>> dates.append('Jun 1 2005  1:33PM')
>>> dates.append('Aug 28 1999 12:00AM')
>>> from datetime import datetime
>>> for d in dates:
...     date = datetime.strptime(d, '%b %d %Y %I:%M%p')
...     print type(date)
...     print date
... 

输出量

<type 'datetime.datetime'>
2005-06-01 13:33:00
<type 'datetime.datetime'>
1999-08-28 00:00:00

如果日期格式不同,可以使用panda或dateutil.parse怎么办?

>>> import dateutil
>>> dates = []
>>> dates.append('12 1 2017')
>>> dates.append('1 1 2017')
>>> dates.append('1 12 2017')
>>> dates.append('June 1 2017 1:30:00AM')
>>> [parser.parse(x) for x in dates]

输出

[datetime.datetime(2017, 12, 1, 0, 0), datetime.datetime(2017, 1, 1, 0, 0), datetime.datetime(2017, 1, 12, 0, 0), datetime.datetime(2017, 6, 1, 1, 30)]

Remember this and you didn’t need to get confused in datetime conversion again.

String to datetime object = strptime

datetime object to other formats = strftime

Jun 1 2005 1:33PM

is equals to

%b %d %Y %I:%M%p

%b Month as locale’s abbreviated name(Jun)

%d Day of the month as a zero-padded decimal number(1)

%Y Year with century as a decimal number(2015)

%I Hour (12-hour clock) as a zero-padded decimal number(01)

%M Minute as a zero-padded decimal number(33)

%p Locale’s equivalent of either AM or PM(PM)

so you need strptime i-e converting string to

>>> dates = []
>>> dates.append('Jun 1 2005  1:33PM')
>>> dates.append('Aug 28 1999 12:00AM')
>>> from datetime import datetime
>>> for d in dates:
...     date = datetime.strptime(d, '%b %d %Y %I:%M%p')
...     print type(date)
...     print date
... 

Output

<type 'datetime.datetime'>
2005-06-01 13:33:00
<type 'datetime.datetime'>
1999-08-28 00:00:00

What if you have different format of dates you can use panda or dateutil.parse

>>> import dateutil
>>> dates = []
>>> dates.append('12 1 2017')
>>> dates.append('1 1 2017')
>>> dates.append('1 12 2017')
>>> dates.append('June 1 2017 1:30:00AM')
>>> [parser.parse(x) for x in dates]

OutPut

[datetime.datetime(2017, 12, 1, 0, 0), datetime.datetime(2017, 1, 1, 0, 0), datetime.datetime(2017, 1, 12, 0, 0), datetime.datetime(2017, 6, 1, 1, 30)]

回答 5

在Python> = 3.7.0中,

转换YYYY-MM-DD字符串DateTime对象datetime.fromisoformat都可以使用。

>>> from datetime import datetime

>>> date_string = "2012-12-12 10:10:10"
>>> print (datetime.fromisoformat(date_string))
>>> 2012-12-12 10:10:10

In Python >= 3.7.0,

to convert YYYY-MM-DD string to datetime object, datetime.fromisoformat could be used.

>>> from datetime import datetime

>>> date_string = "2012-12-12 10:10:10"
>>> print (datetime.fromisoformat(date_string))
>>> 2012-12-12 10:10:10

回答 6

许多时间戳都有一个隐含的时区。为了确保您的代码在每个时区都能工作,您应该在内部使用UTC,并在每次异物进入系统时都附加一个时区。

Python 3.2+:

>>> datetime.datetime.strptime(
...     "March 5, 2014, 20:13:50", "%B %d, %Y, %H:%M:%S"
... ).replace(tzinfo=datetime.timezone(datetime.timedelta(hours=-3)))

Many timestamps have an implied timezone. To ensure that your code will work in every timezone, you should use UTC internally and attach a timezone each time a foreign object enters the system.

Python 3.2+:

>>> datetime.datetime.strptime(
...     "March 5, 2014, 20:13:50", "%B %d, %Y, %H:%M:%S"
... ).replace(tzinfo=datetime.timezone(datetime.timedelta(hours=-3)))

回答 7

这是两个使用Pandas将格式为字符串的日期转换为datetime.date对象的解决方案。

import pandas as pd

dates = ['2015-12-25', '2015-12-26']

# 1) Use a list comprehension.
>>> [d.date() for d in pd.to_datetime(dates)]
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]

# 2) Convert the dates to a DatetimeIndex and extract the python dates.
>>> pd.DatetimeIndex(dates).date.tolist()
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]

时机

dates = pd.DatetimeIndex(start='2000-1-1', end='2010-1-1', freq='d').date.tolist()

>>> %timeit [d.date() for d in pd.to_datetime(dates)]
# 100 loops, best of 3: 3.11 ms per loop

>>> %timeit pd.DatetimeIndex(dates).date.tolist()
# 100 loops, best of 3: 6.85 ms per loop

这是如何转换OP的原始日期时间示例:

datetimes = ['Jun 1 2005  1:33PM', 'Aug 28 1999 12:00AM']

>>> pd.to_datetime(datetimes).to_pydatetime().tolist()
[datetime.datetime(2005, 6, 1, 13, 33), 
 datetime.datetime(1999, 8, 28, 0, 0)]

使用可以从字符串转换为Pandas Timestamps有很多选项to_datetime,因此请检查文档如果需要任何特殊。

同样,时间戳除了具有许多可访问的属性和方法外,.date

Here are two solutions using Pandas to convert dates formatted as strings into datetime.date objects.

import pandas as pd

dates = ['2015-12-25', '2015-12-26']

# 1) Use a list comprehension.
>>> [d.date() for d in pd.to_datetime(dates)]
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]

# 2) Convert the dates to a DatetimeIndex and extract the python dates.
>>> pd.DatetimeIndex(dates).date.tolist()
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]

Timings

dates = pd.DatetimeIndex(start='2000-1-1', end='2010-1-1', freq='d').date.tolist()

>>> %timeit [d.date() for d in pd.to_datetime(dates)]
# 100 loops, best of 3: 3.11 ms per loop

>>> %timeit pd.DatetimeIndex(dates).date.tolist()
# 100 loops, best of 3: 6.85 ms per loop

And here is how to convert the OP’s original date-time examples:

datetimes = ['Jun 1 2005  1:33PM', 'Aug 28 1999 12:00AM']

>>> pd.to_datetime(datetimes).to_pydatetime().tolist()
[datetime.datetime(2005, 6, 1, 13, 33), 
 datetime.datetime(1999, 8, 28, 0, 0)]

There are many options for converting from the strings to Pandas Timestamps using to_datetime, so check the docs if you need anything special.

Likewise, Timestamps have many properties and methods that can be accessed in addition to .date


回答 8

我个人喜欢使用parser模块的解决方案,这是该问题的第二个答案,而且很漂亮,因为您不必构造任何字符串文字即可使其工作。但是,缺点是它比接受的答案慢90%strptime

from dateutil import parser
from datetime import datetime
import timeit

def dt():
    dt = parser.parse("Jun 1 2005  1:33PM")
def strptime():
    datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

print(timeit.timeit(stmt=dt, number=10**5))
print(timeit.timeit(stmt=strptime, number=10**5))
>10.70296801342902
>1.3627995655316933

只要你是不是做这个一百万一遍又一遍的时间,我还是觉得parser方法是更方便,会自动处理大部分的时间格式。

I personally like the solution using the parser module, which is the second Answer to this question and is beautiful, as you don’t have to construct any string literals to get it working. BUT, one downside is that it is 90% slower than the accepted answer with strptime.

from dateutil import parser
from datetime import datetime
import timeit

def dt():
    dt = parser.parse("Jun 1 2005  1:33PM")
def strptime():
    datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

print(timeit.timeit(stmt=dt, number=10**5))
print(timeit.timeit(stmt=strptime, number=10**5))
>10.70296801342902
>1.3627995655316933

As long as you are not doing this a million times over and over again, I still think the parser method is more convenient and will handle most of the time formats automatically.


回答 9

这里没有提到但有用的东西:在一天中添加一个后缀。我解耦了后缀逻辑,以便您可以将其用于任何您喜欢的数字,而不仅仅是日期。

import time

def num_suffix(n):
    '''
    Returns the suffix for any given int
    '''
    suf = ('th','st', 'nd', 'rd')
    n = abs(n) # wise guy
    tens = int(str(n)[-2:])
    units = n % 10
    if tens > 10 and tens < 20:
        return suf[0] # teens with 'th'
    elif units <= 3:
        return suf[units]
    else:
        return suf[0] # 'th'

def day_suffix(t):
    '''
    Returns the suffix of the given struct_time day
    '''
    return num_suffix(t.tm_mday)

# Examples
print num_suffix(123)
print num_suffix(3431)
print num_suffix(1234)
print ''
print day_suffix(time.strptime("1 Dec 00", "%d %b %y"))
print day_suffix(time.strptime("2 Nov 01", "%d %b %y"))
print day_suffix(time.strptime("3 Oct 02", "%d %b %y"))
print day_suffix(time.strptime("4 Sep 03", "%d %b %y"))
print day_suffix(time.strptime("13 Nov 90", "%d %b %y"))
print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))​​​​​​​

Something that isn’t mentioned here and is useful: adding a suffix to the day. I decoupled the suffix logic so you can use it for any number you like, not just dates.

import time

def num_suffix(n):
    '''
    Returns the suffix for any given int
    '''
    suf = ('th','st', 'nd', 'rd')
    n = abs(n) # wise guy
    tens = int(str(n)[-2:])
    units = n % 10
    if tens > 10 and tens < 20:
        return suf[0] # teens with 'th'
    elif units <= 3:
        return suf[units]
    else:
        return suf[0] # 'th'

def day_suffix(t):
    '''
    Returns the suffix of the given struct_time day
    '''
    return num_suffix(t.tm_mday)

# Examples
print num_suffix(123)
print num_suffix(3431)
print num_suffix(1234)
print ''
print day_suffix(time.strptime("1 Dec 00", "%d %b %y"))
print day_suffix(time.strptime("2 Nov 01", "%d %b %y"))
print day_suffix(time.strptime("3 Oct 02", "%d %b %y"))
print day_suffix(time.strptime("4 Sep 03", "%d %b %y"))
print day_suffix(time.strptime("13 Nov 90", "%d %b %y"))
print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))​​​​​​​

回答 10

In [34]: import datetime

In [35]: _now = datetime.datetime.now()

In [36]: _now
Out[36]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000)

In [37]: print _now
2016-01-19 09:47:00.432000

In [38]: _parsed = datetime.datetime.strptime(str(_now),"%Y-%m-%d %H:%M:%S.%f")

In [39]: _parsed
Out[39]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000)

In [40]: assert _now == _parsed
In [34]: import datetime

In [35]: _now = datetime.datetime.now()

In [36]: _now
Out[36]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000)

In [37]: print _now
2016-01-19 09:47:00.432000

In [38]: _parsed = datetime.datetime.strptime(str(_now),"%Y-%m-%d %H:%M:%S.%f")

In [39]: _parsed
Out[39]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000)

In [40]: assert _now == _parsed

回答 11

Django时区感知日期时间对象示例。

import datetime
from django.utils.timezone import get_current_timezone
tz = get_current_timezone()

format = '%b %d %Y %I:%M%p'
date_object = datetime.datetime.strptime('Jun 1 2005  1:33PM', format)
date_obj = tz.localize(date_object)

具备USE_TZ = True以下条件时,此转换对Django和Python非常重要:

RuntimeWarning: DateTimeField MyModel.created received a naive datetime (2016-03-04 00:00:00) while time zone support is active.

Django Timezone aware datetime object example.

import datetime
from django.utils.timezone import get_current_timezone
tz = get_current_timezone()

format = '%b %d %Y %I:%M%p'
date_object = datetime.datetime.strptime('Jun 1 2005  1:33PM', format)
date_obj = tz.localize(date_object)

This conversion is very important for Django and Python when you have USE_TZ = True:

RuntimeWarning: DateTimeField MyModel.created received a naive datetime (2016-03-04 00:00:00) while time zone support is active.

回答 12

创建一个小的实用程序函数,例如:

def date(datestr="", format="%Y-%m-%d"):
    from datetime import datetime
    if not datestr:
        return datetime.today().date()
    return datetime.strptime(datestr, format).date()

这足够通用:

  • 如果您不传递任何参数,它将返回今天的日期。
  • 有一种默认的日期格式可以覆盖。
  • 您可以轻松地对其进行修改以返回日期时间。

Create a small utility function like:

def date(datestr="", format="%Y-%m-%d"):
    from datetime import datetime
    if not datestr:
        return datetime.today().date()
    return datetime.strptime(datestr, format).date()

This is versatile enough:

  • If you don’t pass any arguments it will return today’s date.
  • There’s a date format as default that you can override.
  • You can easily modify it to return a datetime.

回答 13

它将有助于将字符串转换为日期时间以及时区

def convert_string_to_time(date_string, timezone):
    from datetime import datetime
    import pytz
    date_time_obj = datetime.strptime(date_string[:26], '%Y-%m-%d %H:%M:%S.%f')
    date_time_obj_timezone = pytz.timezone(timezone).localize(date_time_obj)

    return date_time_obj_timezone

date = '2018-08-14 13:09:24.543953+00:00'
TIME_ZONE = 'UTC'
date_time_obj_timezone = convert_string_to_time(date, TIME_ZONE)

It would do the helpful for converting string to datetime and also with time zone

def convert_string_to_time(date_string, timezone):
    from datetime import datetime
    import pytz
    date_time_obj = datetime.strptime(date_string[:26], '%Y-%m-%d %H:%M:%S.%f')
    date_time_obj_timezone = pytz.timezone(timezone).localize(date_time_obj)

    return date_time_obj_timezone

date = '2018-08-14 13:09:24.543953+00:00'
TIME_ZONE = 'UTC'
date_time_obj_timezone = convert_string_to_time(date, TIME_ZONE)

回答 14

arrow提供了许多有用的日期和时间功能。这段代码提供了对该问题的答案,并表明箭头还能够轻松格式化日期并显示其他语言环境的信息。

>>> import arrow
>>> dateStrings = [ 'Jun 1  2005 1:33PM', 'Aug 28 1999 12:00AM' ]
>>> for dateString in dateStrings:
...     dateString
...     arrow.get(dateString.replace('  ',' '), 'MMM D YYYY H:mmA').datetime
...     arrow.get(dateString.replace('  ',' '), 'MMM D YYYY H:mmA').format('ddd, Do MMM YYYY HH:mm')
...     arrow.get(dateString.replace('  ',' '), 'MMM D YYYY H:mmA').humanize(locale='de')
...
'Jun 1  2005 1:33PM'
datetime.datetime(2005, 6, 1, 13, 33, tzinfo=tzutc())
'Wed, 1st Jun 2005 13:33'
'vor 11 Jahren'
'Aug 28 1999 12:00AM'
datetime.datetime(1999, 8, 28, 0, 0, tzinfo=tzutc())
'Sat, 28th Aug 1999 00:00'
'vor 17 Jahren'

有关更多信息,请参见http://arrow.readthedocs.io/en/latest/

arrow offers many useful functions for dates and times. This bit of code provides an answer to the question and shows that arrow is also capable of formatting dates easily and displaying information for other locales.

>>> import arrow
>>> dateStrings = [ 'Jun 1  2005 1:33PM', 'Aug 28 1999 12:00AM' ]
>>> for dateString in dateStrings:
...     dateString
...     arrow.get(dateString.replace('  ',' '), 'MMM D YYYY H:mmA').datetime
...     arrow.get(dateString.replace('  ',' '), 'MMM D YYYY H:mmA').format('ddd, Do MMM YYYY HH:mm')
...     arrow.get(dateString.replace('  ',' '), 'MMM D YYYY H:mmA').humanize(locale='de')
...
'Jun 1  2005 1:33PM'
datetime.datetime(2005, 6, 1, 13, 33, tzinfo=tzutc())
'Wed, 1st Jun 2005 13:33'
'vor 11 Jahren'
'Aug 28 1999 12:00AM'
datetime.datetime(1999, 8, 28, 0, 0, tzinfo=tzutc())
'Sat, 28th Aug 1999 00:00'
'vor 17 Jahren'

See http://arrow.readthedocs.io/en/latest/ for more.


回答 15

您可以使用easy_date使其变得容易:

import date_converter
converted_date = date_converter.string_to_datetime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

You can use easy_date to make it easy:

import date_converter
converted_date = date_converter.string_to_datetime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

回答 16

如果只需要日期格式,则可以通过传递各个字段来手动将其转换,例如:

>>> import datetime
>>> date = datetime.date(int('2017'),int('12'),int('21'))
>>> date
datetime.date(2017, 12, 21)
>>> type(date)
<type 'datetime.date'>

您可以传递拆分的字符串值以将其转换为日期类型,例如:

selected_month_rec = '2017-09-01'
date_formate = datetime.date(int(selected_month_rec.split('-')[0]),int(selected_month_rec.split('-')[1]),int(selected_month_rec.split('-')[2]))

您将获得日期格式的结果值。

If you want only date format then you can manually convert it by passing your individual fields like:

>>> import datetime
>>> date = datetime.date(int('2017'),int('12'),int('21'))
>>> date
datetime.date(2017, 12, 21)
>>> type(date)
<type 'datetime.date'>

You can pass your split string values to convert it into date type like:

selected_month_rec = '2017-09-01'
date_formate = datetime.date(int(selected_month_rec.split('-')[0]),int(selected_month_rec.split('-')[1]),int(selected_month_rec.split('-')[2]))

You will get the resulting value in date format.


回答 17

您也可以退房 dateparser

dateparser 提供的模块可轻松解析几乎任何网页上常见的字符串格式的本地化日期。

安装:

$ pip install dateparser

我认为,这是解析日期的最简单方法。

最直接的方法是使用dateparser.parse功能,该功能包装了模块中的大多数功能。

样例代码:

import dateparser

t1 = 'Jun 1 2005  1:33PM'
t2 = 'Aug 28 1999 12:00AM'

dt1 = dateparser.parse(t1)
dt2 = dateparser.parse(t2)

print(dt1)
print(dt2)

输出:

2005-06-01 13:33:00
1999-08-28 00:00:00

You can also check out dateparser

dateparser provides modules to easily parse localized dates in almost any string formats commonly found on web pages.

Install:

$ pip install dateparser

This is, I think, the easiest way you can parse dates.

The most straightforward way is to use the dateparser.parse function, that wraps around most of the functionality in the module.

Sample Code:

import dateparser

t1 = 'Jun 1 2005  1:33PM'
t2 = 'Aug 28 1999 12:00AM'

dt1 = dateparser.parse(t1)
dt2 = dateparser.parse(t2)

print(dt1)
print(dt2)

Output:

2005-06-01 13:33:00
1999-08-28 00:00:00

回答 18

我的回答

在现实世界的数据中,这是一个实际的问题:多种,不匹配,不完整,不一致以及多语言/区域日期格式,通常在一个数据集中自由地混合使用。生产代码失败是不可能的,更不用说像狐狸一样的异常快乐了。

我们需要尝试…捕获多种日期时间格式fmt1,fmt2,…,fmtn,并strptime()为所有不匹配的对象抑制/处理(来自的)异常(尤其是避免使用yukky n缩进的try梯形图) ..catch子句)。从我的解决方案

def try_strptime(s, fmts=['%d-%b-%y','%m/%d/%Y']):
    for fmt in fmts:
        try:
            return datetime.strptime(s, fmt)
        except:
            continue

    return None # or reraise the ValueError if no format matched, if you prefer

See my answer.

In real-world data this is a real problem: multiple, mismatched, incomplete, inconsistent and multilanguage/region date formats, often mixed freely in one dataset. It’s not ok for production code to fail, let alone go exception-happy like a fox.

We need to try…catch multiple datetime formats fmt1,fmt2,…,fmtn and suppress/handle the exceptions (from strptime()) for all those that mismatch (and in particular, avoid needing a yukky n-deep indented ladder of try..catch clauses). From my solution

def try_strptime(s, fmts=['%d-%b-%y','%m/%d/%Y']):
    for fmt in fmts:
        try:
            return datetime.strptime(s, fmt)
        except:
            continue

    return None # or reraise the ValueError if no format matched, if you prefer

回答 19

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")
emp.info()

它显示“开始日期时间”列和“上次登录时间”在数据框中均为“对象=字符串”

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 8 columns):
First Name           933 non-null object
Gender               855 non-null object
Start Date           1000 non-null object

Last Login Time      1000 non-null object
Salary               1000 non-null int64
Bonus %              1000 non-null float64
Senior Management    933 non-null object
Team                 957 non-null object
dtypes: float64(1), int64(1), object(6)
memory usage: 62.6+ KB

通过使用parse_dates选项,read_csv您可以将字符串datetime转换为pandas datetime格式。

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv", parse_dates=["Start Date", "Last Login Time"])
emp.info()


<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 8 columns):
First Name           933 non-null object
Gender               855 non-null object
Start Date           1000 non-null datetime64[ns]
Last Login Time      1000 non-null datetime64[ns]
Salary               1000 non-null int64
Bonus %              1000 non-null float64
Senior Management    933 non-null object
Team                 957 non-null object
dtypes: datetime64[ns](2), float64(1), int64(1), object(4)
memory usage: 62.6+ KB
emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")
emp.info()

it shows “Start Date Time” Column and “Last Login Time” both are “object = strings” in data-frame

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 8 columns):
First Name           933 non-null object
Gender               855 non-null object
Start Date           1000 non-null object

Last Login Time      1000 non-null object
Salary               1000 non-null int64
Bonus %              1000 non-null float64
Senior Management    933 non-null object
Team                 957 non-null object
dtypes: float64(1), int64(1), object(6)
memory usage: 62.6+ KB

By using parse_dates option in read_csv mention you can convert your string datetime into pandas datetime format.

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv", parse_dates=["Start Date", "Last Login Time"])
emp.info()


<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 8 columns):
First Name           933 non-null object
Gender               855 non-null object
Start Date           1000 non-null datetime64[ns]
Last Login Time      1000 non-null datetime64[ns]
Salary               1000 non-null int64
Bonus %              1000 non-null float64
Senior Management    933 non-null object
Team                 957 non-null object
dtypes: datetime64[ns](2), float64(1), int64(1), object(4)
memory usage: 62.6+ KB

如何在Python中获取当前时间

问题:如何在Python中获取当前时间

获取当前时间的模块/方法是什么?

What is the module/method used to get the current time?


回答 0

采用:

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)

>>> print(datetime.datetime.now())
2009-01-06 15:08:24.789150

而只是时间:

>>> datetime.datetime.now().time()
datetime.time(15, 8, 24, 78915)

>>> print(datetime.datetime.now().time())
15:08:24.789150

请参阅文档以获取更多信息。

要保存输入,可以datetimedatetime模块中导入对象:

>>> from datetime import datetime

然后datetime.从以上所有位置移除引线。

Use:

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)

>>> print(datetime.datetime.now())
2009-01-06 15:08:24.789150

And just the time:

>>> datetime.datetime.now().time()
datetime.time(15, 8, 24, 78915)

>>> print(datetime.datetime.now().time())
15:08:24.789150

See the documentation for more information.

To save typing, you can import the datetime object from the datetime module:

>>> from datetime import datetime

Then remove the leading datetime. from all of the above.


回答 1

您可以使用time.strftime()

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

You can use time.strftime():

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

回答 2

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

对于此示例,输出将如下所示: '2013-09-18 11:16:32'

这是strftime指令列表。

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

For this example, the output will be like this: '2013-09-18 11:16:32'

Here is the list of strftime directives.


回答 3

Harley的答案相似,但使用该str()函数可得到快速n脏的,人类可读的格式:

>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'

Similar to Harley’s answer, but use the str() function for a quick-n-dirty, slightly more human readable format:

>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'

回答 4

如何使用Python获取当前时间?

time模块

time模块提供的功能可以告诉我们时间(自纪元以来的秒数)以及其他实用程序。

import time

Unix时代时间

这是保存数据库时应使用的时间戳格式。它是一个简单的浮点数,可以转换为整数。这对于以秒为单位的算术也很有用,因为它代表自1970年1月1日00:00:00以来的秒数,并且相对于我们接下来要看的其他时间表示,它是记忆光。

>>> time.time()
1424233311.771502

该时间戳记不占leap秒,因此不是线性的-leap秒将被忽略。因此,尽管它不等同于国际UTC标准,但它很接近,因此对于大多数记录保存情况而言,这是相当好的。

但是,这对于人工调度而言并不理想。如果您希望在某个特定时间发生将来的事件,则需要使用可以解析为datetime对象或序列化datetime对象的字符串存储该时间(稍后将对此进行描述)。

time.ctime

您还可以用操作系统首选的方式来表示当前时间(这意味着当您更改系统首选项时,它可以更改,因此请不要像其他人所期望的那样,将其作为所有系统的标准时间) 。这通常是用户友好的,但通常不会导致字符串可以按时间顺序排序:

>>> time.ctime()
'Tue Feb 17 23:21:56 2015'

您还可以通过以下方式将时间戳混合为易于阅读的形式ctime

>>> time.ctime(1424233311.771502)
'Tue Feb 17 23:21:51 2015'

这种转换也不利于保存记录(除非只能由人类解析的文本,并且随着光学字符识别和人工智能的改进,我认为这些案件的数量将会减少)。

datetime 模组

datetime模块在这里也非常有用:

>>> import datetime

datetime.datetime.now

datetime.now是一类方法,它返回当前时间。它使用time.localtime不带时区信息的(如果未提供,否则请参阅下面的了解时区)。它具有在外壳上回显的表示形式(允许您重新创建等效的对象),但是在打印(或强制转换为str)时,它具有人类可读(和几乎ISO)的格式,而词典编排相当于按时间顺序排序:

>>> datetime.datetime.now()
datetime.datetime(2015, 2, 17, 23, 43, 49, 94252)
>>> print(datetime.datetime.now())
2015-02-17 23:43:51.782461

日期时间 utcnow

通过执行以下操作,您可以获取全球标准UTC时间中的datetime对象:

>>> datetime.datetime.utcnow()
datetime.datetime(2015, 2, 18, 4, 53, 28, 394163)
>>> print(datetime.datetime.utcnow())
2015-02-18 04:53:31.783988

UTC是几乎等同于GMT时区的时间标准。(虽然GMT和UTC的夏令时不变,但他们的用户可能会在夏季切换到其他时区,例如英国夏令时。)

datetime时区感知

但是,到目前为止,我们创建的datetime对象都无法轻松转换为各种时区。我们可以使用以下pytz模块解决该问题:

>>> import pytz
>>> then = datetime.datetime.now(pytz.utc)
>>> then
datetime.datetime(2015, 2, 18, 4, 55, 58, 753949, tzinfo=<UTC>)

等效地,在Python 3中,我们有一个timezone带有utc timezone实例的类,它也使对象知道时区(但在没有方便的pytz模块的情况下,转换成另一个时区留给读者练习):

>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2015, 2, 18, 22, 31, 56, 564191, tzinfo=datetime.timezone.utc)

而且我们看到我们可以轻松地从原始utc对象转换为时区。

>>> print(then)
2015-02-18 04:55:58.753949+00:00
>>> print(then.astimezone(pytz.timezone('US/Eastern')))
2015-02-17 23:55:58.753949-05:00

您还可以使用pytztimezone localize方法或通过替换tzinfo属性(使用replace,这是盲目的完成)来使朴素的datetime对象知道的,但是这些方法比最佳实践更多的是不得已而为之:

>>> pytz.utc.localize(datetime.datetime.utcnow())
datetime.datetime(2015, 2, 18, 6, 6, 29, 32285, tzinfo=<UTC>)
>>> datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
datetime.datetime(2015, 2, 18, 6, 9, 30, 728550, tzinfo=<UTC>)

pytz模块使我们能够使datetime对象知道时区,并将时间转换为pytz模块中可用的数百个时区。

人们可以表面上连载这个对象UTC时间和存储在数据库中,但它需要远远更多的内存和比简单地存储Unix纪元的时间,这是我第一次表现出更容易出错。

其他查看时间的方式更容易出错,尤其是在处理可能来自不同时区的数据时。您希望不要将字符串或序列化日期时间对象用于哪个时区。

如果您正在使用Python为用户显示时间,则ctime可以很好地工作,而不是在表中(通常排序不佳),而是在时钟中。但是,我个人建议在Python中使用Unix时间或时区感知UTC datetime对象处理时间时。

How do I get the current time in Python?

The time module

The time module provides functions that tells us the time in “seconds since the epoch” as well as other utilities.

import time

Unix Epoch Time

This is the format you should get timestamps in for saving in databases. It is a simple floating point number that can be converted to an integer. It is also good for arithmetic in seconds, as it represents the number of seconds since Jan 1, 1970 00:00:00, and it is memory light relative to the other representations of time we’ll be looking at next:

>>> time.time()
1424233311.771502

This timestamp does not account for leap-seconds, so it’s not linear – leap seconds are ignored. So while it is not equivalent to the international UTC standard, it is close, and therefore quite good for most cases of record-keeping.

This is not ideal for human scheduling, however. If you have a future event you wish to take place at a certain point in time, you’ll want to store that time with a string that can be parsed into a datetime object or a serialized datetime object (these will be described later).

time.ctime

You can also represent the current time in the way preferred by your operating system (which means it can change when you change your system preferences, so don’t rely on this to be standard across all systems, as I’ve seen others expect). This is typically user friendly, but doesn’t typically result in strings one can sort chronologically:

>>> time.ctime()
'Tue Feb 17 23:21:56 2015'

You can hydrate timestamps into human readable form with ctime as well:

>>> time.ctime(1424233311.771502)
'Tue Feb 17 23:21:51 2015'

This conversion is also not good for record-keeping (except in text that will only be parsed by humans – and with improved Optical Character Recognition and Artificial Intelligence, I think the number of these cases will diminish).

datetime module

The datetime module is also quite useful here:

>>> import datetime

datetime.datetime.now

The datetime.now is a class method that returns the current time. It uses the time.localtime without the timezone info (if not given, otherwise see timezone aware below). It has a representation (which would allow you to recreate an equivalent object) echoed on the shell, but when printed (or coerced to a str), it is in human readable (and nearly ISO) format, and the lexicographic sort is equivalent to the chronological sort:

>>> datetime.datetime.now()
datetime.datetime(2015, 2, 17, 23, 43, 49, 94252)
>>> print(datetime.datetime.now())
2015-02-17 23:43:51.782461

datetime’s utcnow

You can get a datetime object in UTC time, a global standard, by doing this:

>>> datetime.datetime.utcnow()
datetime.datetime(2015, 2, 18, 4, 53, 28, 394163)
>>> print(datetime.datetime.utcnow())
2015-02-18 04:53:31.783988

UTC is a time standard that is nearly equivalent to the GMT timezone. (While GMT and UTC do not change for Daylight Savings Time, their users may switch to other timezones, like British Summer Time, during the Summer.)

datetime timezone aware

However, none of the datetime objects we’ve created so far can be easily converted to various timezones. We can solve that problem with the pytz module:

>>> import pytz
>>> then = datetime.datetime.now(pytz.utc)
>>> then
datetime.datetime(2015, 2, 18, 4, 55, 58, 753949, tzinfo=<UTC>)

Equivalently, in Python 3 we have the timezone class with a utc timezone instance attached, which also makes the object timezone aware (but to convert to another timezone without the handy pytz module is left as an exercise to the reader):

>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2015, 2, 18, 22, 31, 56, 564191, tzinfo=datetime.timezone.utc)

And we see we can easily convert to timezones from the original utc object.

>>> print(then)
2015-02-18 04:55:58.753949+00:00
>>> print(then.astimezone(pytz.timezone('US/Eastern')))
2015-02-17 23:55:58.753949-05:00

You can also make a naive datetime object aware with the pytz timezone localize method, or by replacing the tzinfo attribute (with replace, this is done blindly), but these are more last resorts than best practices:

>>> pytz.utc.localize(datetime.datetime.utcnow())
datetime.datetime(2015, 2, 18, 6, 6, 29, 32285, tzinfo=<UTC>)
>>> datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
datetime.datetime(2015, 2, 18, 6, 9, 30, 728550, tzinfo=<UTC>)

The pytz module allows us to make our datetime objects timezone aware and convert the times to the hundreds of timezones available in the pytz module.

One could ostensibly serialize this object for UTC time and store that in a database, but it would require far more memory and be more prone to error than simply storing the Unix Epoch time, which I demonstrated first.

The other ways of viewing times are much more error prone, especially when dealing with data that may come from different time zones. You want there to be no confusion as to which timezone a string or serialized datetime object was intended for.

If you’re displaying the time with Python for the user, ctime works nicely, not in a table (it doesn’t typically sort well), but perhaps in a clock. However, I personally recommend, when dealing with time in Python, either using Unix time, or a timezone aware UTC datetime object.


回答 5

from time import time

t = time()
  • t -浮点数,适用于时间间隔测量。

Unix和Windows平台有所不同。

Do

from time import time

t = time()
  • t – float number, good for time interval measurement.

There is some difference for Unix and Windows platforms.


回答 6

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'

以指定格式输出当前GMT。还有一种localtime()方法。

页面有更多详细信息。

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'

That outputs the current GMT in the specified format. There is also a localtime() method.

This page has more details.


回答 7

先前的答案都是不错的建议,但我发现它最容易使用ctime()

In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'

这样可以很好地格式化当前本地时间的字符串表示形式。

The previous answers are all good suggestions, but I find it easiest to use ctime():

In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'

This gives a nicely formatted string representation of the current local time.


回答 8

最快的方法是:

>>> import time
>>> time.strftime("%Y%m%d")
'20130924'

The quickest way is:

>>> import time
>>> time.strftime("%Y%m%d")
'20130924'

回答 9

如果您需要当前时间作为time对象:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)

If you need current time as a time object:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)

回答 10

.isoformat() 在文档中,但尚未在此处(这与@Ray Vega的答案非常相似):

>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'

.isoformat() is in the documentation, but not yet here (this is mighty similar to @Ray Vega’s answer):

>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'

回答 11

为什么不问美国海军的官方计时器美国海军天文台呢?

import requests
from lxml import html

page = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)
print(tree.xpath('//html//body//h3//pre/text()')[1])

如果您像我一样住在华盛顿特区,那么延迟可能不会太糟糕…

Why not ask the U.S. Naval Observatory, the official timekeeper of the United States Navy?

import requests
from lxml import html

page = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)
print(tree.xpath('//html//body//h3//pre/text()')[1])

If you live in the D.C. area (like me) the latency might not be too bad…


回答 12

使用熊猫来获取当前时间,有点过头了:

import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)

输出:

2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693

Using pandas to get the current time, kind of overkilling the problem at hand:

import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)

Output:

2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693

回答 13

这就是我最终要进行的工作:

>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11

此外,该表是选择适当的格式代码得到格式化只是你想要的方式日期(从Python的“日期时间”的文档的必要参考这里)。

This is what I ended up going with:

>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11

Also, this table is a necessary reference for choosing the appropriate format codes to get the date formatted just the way you want it (from Python “datetime” documentation here).


回答 14

如果您已经在使用numpy,则可以直接使用numpy.datetime64()函数。

import numpy as np
str(np.datetime64('now'))

仅限日期:

str(np.datetime64('today'))

或者,如果您已经在使用熊猫,则可以使用pandas.to_datetime()函数

import pandas as pd
str(pd.to_datetime('now'))

要么,

str(pd.to_datetime('today'))

if you are using numpy already then directly you can use numpy.datetime64() function.

import numpy as np
str(np.datetime64('now'))

for only date:

str(np.datetime64('today'))

or, if you are using pandas already then you can use pandas.to_datetime() function

import pandas as pd
str(pd.to_datetime('now'))

or,

str(pd.to_datetime('today'))

回答 15

您可以使用以下time模块:

import time
print time.strftime("%d/%m/%Y")

>>> 06/02/2015

资本的使用Y给出了全年,而使用则y给出了06/02/15

您还可以使用以下代码来延长时间:

time.strftime("%a, %d %b %Y %H:%M:%S")
>>> 'Fri, 06 Feb 2015 17:45:09'

You can use the time module:

import time
print time.strftime("%d/%m/%Y")

>>> 06/02/2015

The use of the capital Y gives the full year, and using y would give 06/02/15.

You could also use the following code to give a more lengthy time:

time.strftime("%a, %d %b %Y %H:%M:%S")
>>> 'Fri, 06 Feb 2015 17:45:09'

回答 16

datetime.now()返回当前时间作为朴素的datetime对象,该对象表示本地时区中的时间。该值可能不明确,例如在DST转换期间(“回退”)。为避免歧义,应使用UTC时区:

from datetime import datetime

utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417

或具有附加时区信息的时区感知对象(Python 3.2+):

from datetime import datetime, timezone

now = datetime.now(timezone.utc).astimezone()
print(now) # -> 2014-12-23 01:49:25.837541+03:00

datetime.now() returns the current time as a naive datetime object that represents time in the local timezone. That value may be ambiguous e.g., during DST transitions (“fall back”). To avoid ambiguity either UTC timezone should be used:

from datetime import datetime

utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417

Or a timezone-aware object that has the corresponding timezone info attached (Python 3.2+):

from datetime import datetime, timezone

now = datetime.now(timezone.utc).astimezone()
print(now) # -> 2014-12-23 01:49:25.837541+03:00

回答 17

import datetime
date_time = datetime.datetime.now()

date = date_time.date()  # Gives the date
time = date_time.time()  # Gives the time

print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond

dir(date)或任何变量,包括包装。您可以获得与该变量关联的所有属性和方法。

import datetime
date_time = datetime.datetime.now()

date = date_time.date()  # Gives the date
time = date_time.time()  # Gives the time

print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond

Do dir(date) or any variables including the package. You can get all the attributes and methods associated with the variable.


回答 18

>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'
>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'

回答 19

默认情况下,now()函数以YYYY-MM-DD HH:MM:SS:MS格式返回输出。使用以下示例脚本在Python脚本中获取当前日期和时间,并在屏幕上打印结果。创建getDateTime1.py具有以下内容的文件。

import datetime

currentDT = datetime.datetime.now()
print (str(currentDT))

输出如下所示:

2018-03-01 17:03:46.759624

By default, now() function returns output in the YYYY-MM-DD HH:MM:SS:MS format. Use the below sample script to get the current date and time in a Python script and print results on the screen. Create file getDateTime1.py with the below content.

import datetime

currentDT = datetime.datetime.now()
print (str(currentDT))

The output looks like below:

2018-03-01 17:03:46.759624

回答 20

这个问题并不需要仅仅为了它而提供一个新的答案……但是,一个闪亮的新玩具/模块就足够了。那就是Pendulum库,它似乎可以完成arrow尝试的各种工作,但没有固有的缺陷和bug困扰着arrow。

例如,原始问题的答案:

>>> import pendulum
>>> print(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.now('utc'))
2018-08-13T19:29:35.051023+00:00

有很多需要解决的标准,包括多个RFC和ISO。曾经把它们混在一起;不用担心,请看一看dir(pendulum.constants)。不过,这里还有RFC和ISO格式。

当我们说本地的时候,虽然是什么意思?好吧,我的意思是:

>>> print(pendulum.now().timezone_name)
Australia/Melbourne
>>>

大概大多数人都在别的地方。

继续下去。长话短说:Pendulum尝试在日期和时间上执行HTTP请求的操作。值得考虑,尤其是它的易用性和广泛的文档资料。

This question doesn’t need a new answer just for the sake of it … a shiny new-ish toy/module, however, is enough justification. That being the Pendulum library, which appears to do the sort of things which arrow attempted, except without the inherent flaws and bugs which beset arrow.

For instance, the answer to the original question:

>>> import pendulum
>>> print(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.now('utc'))
2018-08-13T19:29:35.051023+00:00

There’s a lot of standards which need addressing, including multiple RFCs and ISOs, to worry about. Ever get them mixed up; not to worry, take a little look into dir(pendulum.constants) There’s a bit more than RFC and ISO formats there, though.

When we say local, though what do we mean? Well I mean:

>>> print(pendulum.now().timezone_name)
Australia/Melbourne
>>>

Presumably most of the rest of you mean somewhere else.

And on it goes. Long story short: Pendulum attempts to do for date and time what requests did for HTTP. It’s worth consideration, particularly for both its ease of use and extensive documentation.


回答 21

时区的当前时间

from datetime import datetime
import pytz

tz_NY = pytz.timezone('America/New_York') 
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))

tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))

tz_India = pytz.timezone('Asia/India')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))

#list timezones
pytz.all_timezones

Current time of a timezone

from datetime import datetime
import pytz

tz_NY = pytz.timezone('America/New_York') 
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))

tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))

tz_India = pytz.timezone('Asia/India')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))

#list timezones
pytz.all_timezones

回答 22

试用http://crsmithdev.com/arrow/中的箭头模块:

import arrow
arrow.now()

或UTC版本:

arrow.utcnow()

要更改其输出,请添加.format():

arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')

对于特定时区:

arrow.now('US/Pacific')

一小时前:

arrow.utcnow().replace(hours=-1)

或者,如果您要要旨。

arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'

Try the arrow module from http://crsmithdev.com/arrow/:

import arrow
arrow.now()

Or the UTC version:

arrow.utcnow()

To change its output, add .format():

arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')

For a specific timezone:

arrow.now('US/Pacific')

An hour ago:

arrow.utcnow().replace(hours=-1)

Or if you want the gist.

arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'

回答 23

我想用毫秒来获取时间。一种简单的获取方法:

import time, datetime

print(datetime.datetime.now().time())                         # 11:20:08.272239

# Or in a more complicated way
print(datetime.datetime.now().time().isoformat())             # 11:20:08.272239
print(datetime.datetime.now().time().strftime('%H:%M:%S.%f')) # 11:20:08.272239

# But do not use this:
print(time.strftime("%H:%M:%S.%f", time.localtime()), str)    # 11:20:08.%f

但是我只想毫秒,对不对?获得它们的最短方法:

import time

time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751

从上一个乘法中添加或删除零以调整小数点位数,或者仅:

def get_time_str(decimal_points=3):
    return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

I want to get the time with milliseconds. A simple way to get them:

import time, datetime

print(datetime.datetime.now().time())                         # 11:20:08.272239

# Or in a more complicated way
print(datetime.datetime.now().time().isoformat())             # 11:20:08.272239
print(datetime.datetime.now().time().strftime('%H:%M:%S.%f')) # 11:20:08.272239

# But do not use this:
print(time.strftime("%H:%M:%S.%f", time.localtime()), str)    # 11:20:08.%f

But I want only milliseconds, right? The shortest way to get them:

import time

time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751

Add or remove zeroes from the last multiplication to adjust number of decimal points, or just:

def get_time_str(decimal_points=3):
    return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

回答 24

您可以使用此功能获取时间(不幸的是,它没有显示AM或PM):

def gettime():
    from datetime import datetime
    return ((str(datetime.now())).split(' ')[1]).split('.')[0]

要获取以后合并的小时,分​​钟,秒和毫秒,可以使用以下功能:

小时:

def gethour():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]

分钟:

def getminute():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]

第二:

def getsecond():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]

毫秒:

def getmillisecond():
    from datetime import datetime
    return (str(datetime.now())).split('.')[1]

You can use this function to get the time (unfortunately it doesn’t say AM or PM):

def gettime():
    from datetime import datetime
    return ((str(datetime.now())).split(' ')[1]).split('.')[0]

To get the hours, minutes, seconds and milliseconds to merge later, you can use these functions:

Hour:

def gethour():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]

Minute:

def getminute():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]

Second:

def getsecond():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]

Millisecond:

def getmillisecond():
    from datetime import datetime
    return (str(datetime.now())).split('.')[1]

回答 25

如果只需要当前时间戳(以毫秒为单位)(例如,测量执行时间),则也可以使用“ timeit”模块:

import timeit
start_time = timeit.default_timer()
do_stuff_you_want_to_measure()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))

If you just want the current timestamp in ms (for example, to measure execution time), you can also use the “timeit” module:

import timeit
start_time = timeit.default_timer()
do_stuff_you_want_to_measure()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))

回答 26

以下是我用来获取时间而不必进行格式化的内容。有些人不喜欢split方法,但是在这里很有用:

from time import ctime
print ctime().split()[3]

它将以HH:MM:SS格式打印。

The following is what I use to get the time without having to format. Some people don’t like the split method, but it is useful here:

from time import ctime
print ctime().split()[3]

It will print in HH:MM:SS format.


回答 27

因为还没有人提及它,所以我最近遇到了这个问题……pytz时区的fromutc()方法与datetime的utcnow()结合是我发现获得有用的当前时间(和日期)的最佳方法在任何时区。

from datetime import datetime

import pytz


JST = pytz.timezone("Asia/Tokyo")


local_time = JST.fromutc(datetime.utcnow())

如果您想要的只是时间,那么您可以使用local_time.time()

Because no one has mentioned it yet, and this is something I ran into recently… a pytz timezone’s fromutc() method combined with datetime’s utcnow() is the best way I’ve found to get a useful current time (and date) in any timezone.

from datetime import datetime

import pytz


JST = pytz.timezone("Asia/Tokyo")


local_time = JST.fromutc(datetime.utcnow())

If all you want is the time, you can then get that with local_time.time().


回答 28

这个问题是针对Python的,但是由于Django是Python使用最广泛的框架之一,因此必须注意,如果您使用的是Django,则可以始终使用timezone.now()而不是datetime.datetime.now()。前者是时区“知道”的,而后者则不是。

请参阅此SO答案Django文档,以获取详细信息和背后的原理timezone.now()

from django.utils import timezone

now = timezone.now()

This question is for Python but since Django is one of the most widely used frameworks for Python, its important to note that if you are using Django you can always use timezone.now() instead of datetime.datetime.now(). The former is timezone ‘aware’ while the latter is not.

See this SO answer and the Django doc for details and rationale behind timezone.now().

from django.utils import timezone

now = timezone.now()

回答 29

您可以使用ctime()来做到这一点:

from time import time, ctime
t = time()
ctime(t)

输出:

Sat Sep 14 21:27:08 2019

这些输出是不同的,因为返回的时间戳ctime()取决于您的地理位置。

You can do so using ctime():

from time import time, ctime
t = time()
ctime(t)

output:

Sat Sep 14 21:27:08 2019

These outputs are different because the timestamp returned by ctime() depends on your geographical location.


Arrow-更好的Python日期和时间

Arrow:Python更好的日期和时间

Arrow是一个Python库,它为创建、操作、格式化和转换日期、时间和时间戳提供了一种明智且人性化的方法。它实现并更新了DateTime类型,填补了功能上的空白,并提供了支持许多常见创建场景的智能模块API。简单地说,它帮助您使用更少的导入和更少的代码来处理日期和时间

Arrow以arrow of time在很大程度上受到了moment.jsrequests

为什么要使用Arrow而不是内置模块?

Python的标准库和其他一些低级模块具有近乎完整的日期、时间和时区功能,但从可用性的角度来看,它们工作得不是很好:

  • 模块太多:DateTime、Time、Calendar、Dateutil、pytz等等
  • 类型太多:Date、Time、DateTime、tzinfo、Time Delta、Relativedelta等
  • 时区和时间戳转换既冗长又令人不快
  • 时区天真是常态
  • 功能差距:ISO 8601解析、时间跨度、人性化

功能

  • DateTime的完全实现的插入式替代
  • 支持Python 3.6+
  • 默认情况下支持时区和UTC
  • 针对许多常见输入方案的超简单创建选项
  • shift支持相对偏移量(包括周)的方法
  • 自动格式化和解析字符串
  • 广泛支持ISO 8601标准
  • 时区转换
  • 支持dateutilpytz,以及ZoneInfotzinfo对象
  • 为从微秒到一年的时间范围生成时间跨度、范围、下限和上限
  • 通过不断增加的区域设置列表,使日期和时间人性化
  • 可扩展到您自己的Arrow派生类型
  • 完全支持PEP 484样式的类型提示

快速入门

安装

要安装Arrow,请使用pippipenv

$ pip install -U arrow

用法示例

>>> import arrow
>>> arrow.get('2013-05-11T21:23:58.970460+07:00')
<Arrow [2013-05-11T21:23:58.970460+07:00]>

>>> utc = arrow.utcnow()
>>> utc
<Arrow [2013-05-11T21:23:58.970460+00:00]>

>>> utc = utc.shift(hours=-1)
>>> utc
<Arrow [2013-05-11T20:23:58.970460+00:00]>

>>> local = utc.to('US/Pacific')
>>> local
<Arrow [2013-05-11T13:23:58.970460-07:00]>

>>> local.timestamp()
1368303838.970460

>>> local.format()
'2013-05-11 13:23:58 -07:00'

>>> local.format('YYYY-MM-DD HH:mm:ss ZZ')
'2013-05-11 13:23:58 -07:00'

>>> local.humanize()
'an hour ago'

>>> local.humanize(locale='ko-kr')
'한시간 전'

文档

有关完整文档,请访问arrow.readthedocs.io

贡献

代码和本地化(添加和更新区域设置)都欢迎贡献。首先熟悉Arrow库及其功能。然后,开始投身于贡献吧:

  1. 在撞击上查找问题或功能issue tracker标记为“good first issue” label可能是一个很好的起点!
  2. 叉子this repository在GitHub上,并开始在分支机构中进行更改
  3. 添加一些测试以确保错误已修复或功能按预期工作
  4. 通过运行以下命令之一运行整个测试套件和linting检查:tox && tox -e lint,docs(如果您有tox已安装)make build39 && make test && make lint(如果未安装Python 3.9,请替换build39在您的系统上安装最新的Python版本)
  5. 提交拉取请求并等待反馈😃

如果你在路上有什么问题,尽管问。here

支撑箭头

Open Collective是一个在线融资平台,提供工具来筹集资金,并在完全透明的情况下分享您的财务。它是个人和公司直接向该项目进行一次性或经常性捐款的首选平台。如果您有兴趣捐款,请浏览Arrow collective