标签归档:date

在Python中将日期转换为日期时间

问题:在Python中将日期转换为日期时间

是否有一个内置的转换方法datedatetime在Python,例如获得datetime在指定日期的午夜?相反的转换很容易:datetime有一个.date()方法。

我真的必须手动打电话datetime(d.year, d.month, d.day)吗?

Is there a built-in method for converting a date to a datetime in Python, for example getting the datetime for the midnight of the given date? The opposite conversion is easy: datetime has a .date() method.

Do I really have to manually call datetime(d.year, d.month, d.day)?


回答 0

您可以使用datetime.combine(date, time);现在,您创建一个datetime.time初始化为午夜的对象。

from datetime import date
from datetime import datetime

dt = datetime.combine(date.today(), datetime.min.time())

You can use datetime.combine(date, time); for the time, you create a datetime.time object initialized to midnight.

from datetime import date
from datetime import datetime

dt = datetime.combine(date.today(), datetime.min.time())

回答 1

尽管我确实相信您提到(和不喜欢)的方法是最易读的方法,但是有几种方法。

>>> t=datetime.date.today()
>>> datetime.datetime.fromordinal(t.toordinal())
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(t.year, t.month, t.day)
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(*t.timetuple()[:-4])
datetime.datetime(2009, 12, 20, 0, 0)

依此类推-但基本上它们都取决于从date对象中适当地提取信息并将其犁入合适的ctor或classfunction中datetime

There are several ways, although I do believe the one you mention (and dislike) is the most readable one.

>>> t=datetime.date.today()
>>> datetime.datetime.fromordinal(t.toordinal())
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(t.year, t.month, t.day)
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(*t.timetuple()[:-4])
datetime.datetime(2009, 12, 20, 0, 0)

and so forth — but basically they all hinge on appropriately extracting info from the date object and ploughing it back into the suitable ctor or classfunction for datetime.


回答 2

可接受的答案是正确的,但我宁愿避免使用datetime.min.time()它,因为它对我的确切作用并不明显。如果对您而言显而易见,那么您将拥有更多权力。我也对timetuple方法和对订购的依赖的看法。

我认为,在不依赖读者非常熟悉datetime模块API的情况下,最易读,明确的方式是:

from datetime import date, datetime
today = date.today()
today_with_time = datetime(
    year=today.year, 
    month=today.month,
    day=today.day,
)

这就是我对“明确胜于隐含”的看法。

The accepted answer is correct, but I would prefer to avoid using datetime.min.time() because it’s not obvious to me exactly what it does. If it’s obvious to you, then more power to you. I also feel the same way about the timetuple method and the reliance on the ordering.

In my opinion, the most readable, explicit way of doing this without relying on the reader to be very familiar with the datetime module API is:

from datetime import date, datetime
today = date.today()
today_with_time = datetime(
    year=today.year, 
    month=today.month,
    day=today.day,
)

That’s my take on “explicit is better than implicit.”


回答 3

您可以使用date.timetuple()method和unpack运算符*

args = d.timetuple()[:6]
datetime.datetime(*args)

You can use the date.timetuple() method and unpack operator *.

args = d.timetuple()[:6]
datetime.datetime(*args)

回答 4

今天是2016年,我认为pandas Timestamp提供了最干净的解决方案:

from datetime import date
import pandas as pd
d = date.today()
pd.Timestamp(d)

时间戳等于日期时间的大熊猫,并且在大多数情况下可以互换。校验:

from datetime import datetime
isinstance(pd.Timestamp(d), datetime)

但是,如果您真的想要一个普通的日期时间,您仍然可以执行以下操作:

pd.Timestamp(d).to_datetime()

时间戳比日期时间强大得多,尤其是在处理时区时。实际上,时间戳记是如此强大,以至于它们的文献记录如此之少,实在令人遗憾。

Today being 2016, I think the cleanest solution is provided by pandas Timestamp:

from datetime import date
import pandas as pd
d = date.today()
pd.Timestamp(d)

Timestamp is the pandas equivalent of datetime and is interchangable with it in most cases. Check:

from datetime import datetime
isinstance(pd.Timestamp(d), datetime)

But in case you really want a vanilla datetime, you can still do:

pd.Timestamp(d).to_datetime()

Timestamps are a lot more powerful than datetimes, amongst others when dealing with timezones. Actually, Timestamps are so powerful that it’s a pity they are so poorly documented…


回答 5

尚未提到的将日期转换为日期时间的一种方法:

from datetime import date, datetime
d = date.today()
datetime.strptime(d.strftime('%Y%m%d'), '%Y%m%d')

One way to convert from date to datetime that hasn’t been mentioned yet:

from datetime import date, datetime
d = date.today()
datetime.strptime(d.strftime('%Y%m%d'), '%Y%m%d')

回答 6

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

import date_converter
my_datetime = date_converter.date_to_datetime(my_date)

You can use easy_date to make it easy:

import date_converter
my_datetime = date_converter.date_to_datetime(my_date)

回答 7

如果您需要快速操作,请datetime_object.date()给您一个datetime对象的日期。

If you need something quick, datetime_object.date() gives you a date of a datetime object.


回答 8

我是Python的新手。但是这段代码对我有用,它将我提供的指定输入转换为datetime。这是代码。如我错了请纠正我。

import sys
from datetime import datetime
from time import mktime, strptime

user_date = '02/15/1989'
if user_date is not None:
     user_date = datetime.strptime(user_date,"%m/%d/%Y")
else:
     user_date = datetime.now()
print user_date

I am a newbie to Python. But this code worked for me which converts the specified input I provide to datetime. Here’s the code. Correct me if I’m wrong.

import sys
from datetime import datetime
from time import mktime, strptime

user_date = '02/15/1989'
if user_date is not None:
     user_date = datetime.strptime(user_date,"%m/%d/%Y")
else:
     user_date = datetime.now()
print user_date

如何计算两个给定日期之间的天数?

问题:如何计算两个给定日期之间的天数?

如果我有两个日期(例如'8/18/2008''9/26/2008'),获取这两个日期之间的天数的最佳方法是什么?

If I have two dates (ex. '8/18/2008' and '9/26/2008'), what is the best way to get the number of days between these two dates?


回答 0

如果您有两个日期对象,则可以减去它们,从而计算出一个timedelta对象。

from datetime import date

d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)

文档的相关部分:https : //docs.python.org/library/datetime.html

参见此答案的另一个示例。

If you have two date objects, you can just subtract them, which computes a timedelta object.

from datetime import date

d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)

The relevant section of the docs: https://docs.python.org/library/datetime.html.

See this answer for another example.


回答 1

使用datetime的功能:

from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime('8/18/2008', date_format)
b = datetime.strptime('9/26/2008', date_format)
delta = b - a
print delta.days # that's it

Using the power of datetime:

from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime('8/18/2008', date_format)
b = datetime.strptime('9/26/2008', date_format)
delta = b - a
print delta.days # that's it

回答 2

直到圣诞节的天数:

>>> import datetime
>>> today = datetime.date.today()
>>> someday = datetime.date(2008, 12, 25)
>>> diff = someday - today
>>> diff.days
86

这里有更多的算术。

Days until Christmas:

>>> import datetime
>>> today = datetime.date.today()
>>> someday = datetime.date(2008, 12, 25)
>>> diff = someday - today
>>> diff.days
86

More arithmetic here.


回答 3

您需要datetime模块。

>>> from datetime import datetime, timedelta 
>>> datetime(2008,08,18) - datetime(2008,09,26) 
datetime.timedelta(4) 

另一个例子:

>>> import datetime 
>>> today = datetime.date.today() 
>>> print(today)
2008-09-01 
>>> last_year = datetime.date(2007, 9, 1) 
>>> print(today - last_year)
366 days, 0:00:00 

正如这里指出的

You want the datetime module.

>>> from datetime import datetime, timedelta 
>>> datetime(2008,08,18) - datetime(2008,09,26) 
datetime.timedelta(4) 

Another example:

>>> import datetime 
>>> today = datetime.date.today() 
>>> print(today)
2008-09-01 
>>> last_year = datetime.date(2007, 9, 1) 
>>> print(today - last_year)
366 days, 0:00:00 

As pointed out here


回答 4

from datetime import datetime
start_date = datetime.strptime('8/18/2008', "%m/%d/%Y")
end_date = datetime.strptime('9/26/2008', "%m/%d/%Y")
print abs((end_date-start_date).days)
from datetime import datetime
start_date = datetime.strptime('8/18/2008', "%m/%d/%Y")
end_date = datetime.strptime('9/26/2008', "%m/%d/%Y")
print abs((end_date-start_date).days)

回答 5

也可以通过以下操作轻松完成arrow

import arrow

a = arrow.get('2017-05-09')
b = arrow.get('2017-05-11')

delta = (b-a)
print delta.days

供参考:http : //arrow.readthedocs.io/en/latest/

It also can be easily done with arrow:

import arrow

a = arrow.get('2017-05-09')
b = arrow.get('2017-05-11')

delta = (b-a)
print delta.days

For reference: http://arrow.readthedocs.io/en/latest/


回答 6

不使用Lib只是纯代码:

#Calculate the Days between Two Date

daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

def isLeapYear(year):

    # Pseudo code for this algorithm is found at
    # http://en.wikipedia.org/wiki/Leap_year#Algorithm
    ## if (year is not divisible by 4) then (it is a common Year)
    #else if (year is not divisable by 100) then (ut us a leap year)
    #else if (year is not disible by 400) then (it is a common year)
    #else(it is aleap year)
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

def Count_Days(year1, month1, day1):
    if month1 ==2:
        if isLeapYear(year1):
            if day1 < daysOfMonths[month1-1]+1:
                return year1, month1, day1+1
            else:
                if month1 ==12:
                    return year1+1,1,1
                else:
                    return year1, month1 +1 , 1
        else: 
            if day1 < daysOfMonths[month1-1]:
                return year1, month1, day1+1
            else:
                if month1 ==12:
                    return year1+1,1,1
                else:
                    return year1, month1 +1 , 1
    else:
        if day1 < daysOfMonths[month1-1]:
             return year1, month1, day1+1
        else:
            if month1 ==12:
                return year1+1,1,1
            else:
                    return year1, month1 +1 , 1


def daysBetweenDates(y1, m1, d1, y2, m2, d2,end_day):

    if y1 > y2:
        m1,m2 = m2,m1
        y1,y2 = y2,y1
        d1,d2 = d2,d1
    days=0
    while(not(m1==m2 and y1==y2 and d1==d2)):
        y1,m1,d1 = Count_Days(y1,m1,d1)
        days+=1
    if end_day:
        days+=1
    return days


# Test Case

def test():
    test_cases = [((2012,1,1,2012,2,28,False), 58), 
                  ((2012,1,1,2012,3,1,False), 60),
                  ((2011,6,30,2012,6,30,False), 366),
                  ((2011,1,1,2012,8,8,False), 585 ),
                  ((1994,5,15,2019,8,31,False), 9239),
                  ((1999,3,24,2018,2,4,False), 6892),
                  ((1999,6,24,2018,8,4,False),6981),
                  ((1995,5,24,2018,12,15,False),8606),
                  ((1994,8,24,2019,12,15,True),9245),
                  ((2019,12,15,1994,8,24,True),9245),
                  ((2019,5,15,1994,10,24,True),8970),
                  ((1994,11,24,2019,8,15,True),9031)]

    for (args, answer) in test_cases:
        result = daysBetweenDates(*args)
        if result != answer:
            print "Test with data:", args, "failed"
        else:
            print "Test case passed!"

test()

without using Lib just pure code:

#Calculate the Days between Two Date

daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

def isLeapYear(year):

    # Pseudo code for this algorithm is found at
    # http://en.wikipedia.org/wiki/Leap_year#Algorithm
    ## if (year is not divisible by 4) then (it is a common Year)
    #else if (year is not divisable by 100) then (ut us a leap year)
    #else if (year is not disible by 400) then (it is a common year)
    #else(it is aleap year)
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

def Count_Days(year1, month1, day1):
    if month1 ==2:
        if isLeapYear(year1):
            if day1 < daysOfMonths[month1-1]+1:
                return year1, month1, day1+1
            else:
                if month1 ==12:
                    return year1+1,1,1
                else:
                    return year1, month1 +1 , 1
        else: 
            if day1 < daysOfMonths[month1-1]:
                return year1, month1, day1+1
            else:
                if month1 ==12:
                    return year1+1,1,1
                else:
                    return year1, month1 +1 , 1
    else:
        if day1 < daysOfMonths[month1-1]:
             return year1, month1, day1+1
        else:
            if month1 ==12:
                return year1+1,1,1
            else:
                    return year1, month1 +1 , 1


def daysBetweenDates(y1, m1, d1, y2, m2, d2,end_day):

    if y1 > y2:
        m1,m2 = m2,m1
        y1,y2 = y2,y1
        d1,d2 = d2,d1
    days=0
    while(not(m1==m2 and y1==y2 and d1==d2)):
        y1,m1,d1 = Count_Days(y1,m1,d1)
        days+=1
    if end_day:
        days+=1
    return days


# Test Case

def test():
    test_cases = [((2012,1,1,2012,2,28,False), 58), 
                  ((2012,1,1,2012,3,1,False), 60),
                  ((2011,6,30,2012,6,30,False), 366),
                  ((2011,1,1,2012,8,8,False), 585 ),
                  ((1994,5,15,2019,8,31,False), 9239),
                  ((1999,3,24,2018,2,4,False), 6892),
                  ((1999,6,24,2018,8,4,False),6981),
                  ((1995,5,24,2018,12,15,False),8606),
                  ((1994,8,24,2019,12,15,True),9245),
                  ((2019,12,15,1994,8,24,True),9245),
                  ((2019,5,15,1994,10,24,True),8970),
                  ((1994,11,24,2019,8,15,True),9031)]

    for (args, answer) in test_cases:
        result = daysBetweenDates(*args)
        if result != answer:
            print "Test with data:", args, "failed"
        else:
            print "Test case passed!"

test()

回答 7

每个人都很好地用日期回答了,让我尝试用熊猫来回答

dt = pd.to_datetime('2008/08/18', format='%Y/%m/%d')
dt1 = pd.to_datetime('2008/09/26', format='%Y/%m/%d')

(dt1-dt).days

这将给出答案。如果输入之一是dataframe列。只需使用dt.days代替days

(dt1-dt).dt.days

everyone has answered excellently using the date, let me try to answer it using pandas

dt = pd.to_datetime('2008/08/18', format='%Y/%m/%d')
dt1 = pd.to_datetime('2008/09/26', format='%Y/%m/%d')

(dt1-dt).days

This will give the answer. In case one of the input is dataframe column. simply use dt.days in place of days

(dt1-dt).dt.days

回答 8

还有一种datetime.toordinal()尚未提及的方法:

import datetime
print(datetime.date(2008,9,26).toordinal() - datetime.date(2008,8,18).toordinal())  # 39

https://docs.python.org/3/library/datetime.html#datetime.date.toordinal

date.toordinal()

返回日期,其中1月1日1年的有序1.对于任何的proleptic阳历序date对象ddate.fromordinal(d.toordinal()) == d

似乎很适合计算天差,尽管不如timedelta.days

There is also a datetime.toordinal() method that was not mentioned yet:

import datetime
print(datetime.date(2008,9,26).toordinal() - datetime.date(2008,8,18).toordinal())  # 39

https://docs.python.org/3/library/datetime.html#datetime.date.toordinal

date.toordinal()

Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. For any date object d, date.fromordinal(d.toordinal()) == d.

Seems well suited for calculating days difference, though not as readable as timedelta.days.


回答 9

为了计算日期和时间,有几种选择,但是我将编写简单的方法:

from datetime import timedelta, datetime, date
import dateutil.relativedelta

# current time
date_and_time = datetime.datetime.now()
date_only = date.today()
time_only = datetime.datetime.now().time()

# calculate date and time
result = date_and_time - datetime.timedelta(hours=26, minutes=25, seconds=10)

# calculate dates: years (-/+)
result = date_only - dateutil.relativedelta.relativedelta(years=10)

# months
result = date_only - dateutil.relativedelta.relativedelta(months=10)

# days
result = date_only - dateutil.relativedelta.relativedelta(days=10)

# calculate time 
result = date_and_time - datetime.timedelta(hours=26, minutes=25, seconds=10)
result.time()

希望能帮助到你

For calculating dates and times, there are several options but I will write the simple way:

from datetime import timedelta, datetime, date
import dateutil.relativedelta

# current time
date_and_time = datetime.datetime.now()
date_only = date.today()
time_only = datetime.datetime.now().time()

# calculate date and time
result = date_and_time - datetime.timedelta(hours=26, minutes=25, seconds=10)

# calculate dates: years (-/+)
result = date_only - dateutil.relativedelta.relativedelta(years=10)

# months
result = date_only - dateutil.relativedelta.relativedelta(months=10)

# days
result = date_only - dateutil.relativedelta.relativedelta(days=10)

# calculate time 
result = date_and_time - datetime.timedelta(hours=26, minutes=25, seconds=10)
result.time()

Hope it helps


回答 10

from datetime import date
def d(s):
  [month, day, year] = map(int, s.split('/'))
  return date(year, month, day)
def days(start, end):
  return (d(end) - d(start)).days
print days('8/18/2008', '9/26/2008')

当然,这是假设您已经确认日期采用格式r'\d+/\d+/\d+'

from datetime import date
def d(s):
  [month, day, year] = map(int, s.split('/'))
  return date(year, month, day)
def days(start, end):
  return (d(end) - d(start)).days
print days('8/18/2008', '9/26/2008')

This assumes, of course, that you’ve already verified that your dates are in the format r'\d+/\d+/\d+'.


回答 11

以下是解决此问题的三种方法:

from datetime import datetime

Now = datetime.now()
StartDate = datetime.strptime(str(Now.year) +'-01-01', '%Y-%m-%d')
NumberOfDays = (Now - StartDate)

print(NumberOfDays.days)                     # Starts at 0
print(datetime.now().timetuple().tm_yday)    # Starts at 1
print(Now.strftime('%j'))                    # Starts at 1

Here are three ways to go with this problem :

from datetime import datetime

Now = datetime.now()
StartDate = datetime.strptime(str(Now.year) +'-01-01', '%Y-%m-%d')
NumberOfDays = (Now - StartDate)

print(NumberOfDays.days)                     # Starts at 0
print(datetime.now().timetuple().tm_yday)    # Starts at 1
print(Now.strftime('%j'))                    # Starts at 1

如何从日期中减去一天?

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

我有一个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')]

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