标签归档:datetime

如何在Python中获取星期数?

问题:如何在Python中获取星期数?

如何使用Python找出6月16日(wk24)当年的星期几?

How to find out what week number is current year on June 16th (wk24) with Python?


回答 0

datetime.date有一个isocalendar()方法,该方法返回包含日历周的元组:

>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar()[1]
24

datetime.date.isocalendar()是一种实例方法,该方法返回给定日期实例的元组,该元组按各自的顺序包含年,周号和周日。

datetime.date has a isocalendar() method, which returns a tuple containing the calendar week:

>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar()[1]
24

datetime.date.isocalendar() is an instance-method returning a tuple containing year, weeknumber and weekday in respective order for the given date instance.


回答 1

您可以直接从日期时间获取星期数作为字符串。

>>> import datetime
>>> datetime.date(2010, 6, 16).strftime("%V")
'24'

您还可以通过更改以下strftime参数来获得一年中星期几的不同“类型” :

%U一年中的周号(星期日为一周的第一天),以零填充的十进制数表示。在第一个星期天之前的新的一年的所有天都被认为是在本周0示例:00,01,…,53

%W-一年中的星期数(星期一为一周的第一天),以十进制数表示。第一个星期一之前的新的一年中的所有天都视为在第0周。例如:00,01,…,53

[…]

在Python 3.6中添加,并反向移植到某些发行版的Python 2.7中。)为方便起见,还包含了C89标准不需要的其他一些指令。这些参数都对应于ISO 8601日期值。当与该strftime()方法一起使用时,可能并非在所有平台上都可用。

[…]

%VISO 8601星期与周一的十进制数作为一周的第一天。周01是包含在1月4例子的一周:01,02,…,53

from:datetime-基本日期和时间类型-Python 3.7.3文档

我从这里找到了。它在Python 2.7.6中为我工作

You can get the week number directly from datetime as string.

>>> import datetime
>>> datetime.date(2010, 6, 16).strftime("%V")
'24'

Also you can get different “types” of the week number of the year changing the strftime parameter for:

%UWeek number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. Examples: 00, 01, …, 53

%W – Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. Examples: 00, 01, …, 53

[…]

(Added in Python 3.6, backported to some distribution’s Python 2.7’s) Several additional directives not required by the C89 standard are included for convenience. These parameters all correspond to ISO 8601 date values. These may not be available on all platforms when used with the strftime() method.

[…]

%VISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4. Examples: 01, 02, …, 53

from: datetime — Basic date and time types — Python 3.7.3 documentation

I’ve found out about it from here. It worked for me in Python 2.7.6


回答 2

我相信date.isocalendar()这将是答案。本文介绍了ISO 8601日历背后的数学原理。查看Python文档的datetime页面的date.isocalendar()部分。

>>> dt = datetime.date(2010, 6, 16) 
>>> wk = dt.isocalendar()[1]
24

.isocalendar()返回带有(年,周,周,日)的三元组。dt.isocalendar()[0]返回年份,dt.isocalendar()[1]返回星期数,dt.isocalendar()[2]返回星期几。可以很简单。

I believe date.isocalendar() is going to be the answer. This article explains the math behind ISO 8601 Calendar. Check out the date.isocalendar() portion of the datetime page of the Python documentation.

>>> dt = datetime.date(2010, 6, 16) 
>>> wk = dt.isocalendar()[1]
24

.isocalendar() return a 3-tuple with (year, wk num, wk day). dt.isocalendar()[0] returns the year,dt.isocalendar()[1] returns the week number, dt.isocalendar()[2] returns the week day. Simple as can be.


回答 3

这是另一个选择:

import time
from time import gmtime, strftime
d = time.strptime("16 Jun 2010", "%d %b %Y")
print(strftime("%U", d))

哪个打印 24

请参阅:http//docs.python.org/library/datetime.html#strftime-and-strptime-behavior

Here’s another option:

import time
from time import gmtime, strftime
d = time.strptime("16 Jun 2010", "%d %b %Y")
print(strftime("%U", d))

which prints 24.

See: http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior


回答 4

其他人建议的ISO周是不错的一周,但它可能不符合您的需求。假设每个星期都从星期一开始,这会导致年初和年底出现一些有趣的异常情况。

如果您想使用第1周始终为1月1日至1月7日的定义,而不管一周中的星期几,请使用类似以下的推导:

>>> testdate=datetime.datetime(2010,6,16)
>>> print(((testdate - datetime.datetime(testdate.year,1,1)).days // 7) + 1)
24

The ISO week suggested by others is a good one, but it might not fit your needs. It assumes each week begins with a Monday, which leads to some interesting anomalies at the beginning and end of the year.

If you’d rather use a definition that says week 1 is always January 1 through January 7, regardless of the day of the week, use a derivation like this:

>>> testdate=datetime.datetime(2010,6,16)
>>> print(((testdate - datetime.datetime(testdate.year,1,1)).days // 7) + 1)
24

回答 5

通常要获取当前的星期数(从星期日开始):

from datetime import *
today = datetime.today()
print today.strftime("%U")

Generally to get the current week number (starts from Sunday):

from datetime import *
today = datetime.today()
print today.strftime("%U")

回答 6

对于一年中瞬时周的整数值,请尝试:

import datetime
datetime.datetime.utcnow().isocalendar()[1]

For the integer value of the instantaneous week of the year try:

import datetime
datetime.datetime.utcnow().isocalendar()[1]

回答 7

许多用于周编号的系统。以下是简单地与代码示例一起放置的最常见系统:

  • ISO:第一周从星期一开始,必须包含1月4日。ISO日历已在Python中实现:

    >>> from datetime import date
    >>> date(2014, 12, 29).isocalendar()[:2]
    (2015, 1)
  • 北美:第一周从星期日开始,必须包含1月1日。以下代码是针对北美系统的Python ISO日历实现的修改后的版本:

    from datetime import date
    
    def week_from_date(date_object):
        date_ordinal = date_object.toordinal()
        year = date_object.year
        week = ((date_ordinal - _week1_start_ordinal(year)) // 7) + 1
        if week >= 52:
            if date_ordinal >= _week1_start_ordinal(year + 1):
                year += 1
                week = 1
        return year, week
    
    def _week1_start_ordinal(year):
        jan1 = date(year, 1, 1)
        jan1_ordinal = jan1.toordinal()
        jan1_weekday = jan1.weekday()
        week1_start_ordinal = jan1_ordinal - ((jan1_weekday + 1) % 7)
        return week1_start_ordinal
    >>> from datetime import date
    >>> week_from_date(date(2014, 12, 29))
    (2015, 1)
  • MMWR(CDC):第一周从星期日开始,必须包含1月4日。我专门为此编号系统创建了epiweeks程序包(也支持ISO系统)。这是一个例子:
    >>> from datetime import date
    >>> from epiweeks import Week
    >>> Week.fromdate(date(2014, 12, 29))
    (2014, 53)

There are many systems for week numbering. The following are the most common systems simply put with code examples:

  • ISO: First week starts with Monday and must contain the January 4th. The ISO calendar is already implemented in Python:

    >>> from datetime import date
    >>> date(2014, 12, 29).isocalendar()[:2]
    (2015, 1)
    
  • North American: First week starts with Sunday and must contain the January 1st. The following code is my modified version of Python’s ISO calendar implementation for the North American system:

    from datetime import date
    
    def week_from_date(date_object):
        date_ordinal = date_object.toordinal()
        year = date_object.year
        week = ((date_ordinal - _week1_start_ordinal(year)) // 7) + 1
        if week >= 52:
            if date_ordinal >= _week1_start_ordinal(year + 1):
                year += 1
                week = 1
        return year, week
    
    def _week1_start_ordinal(year):
        jan1 = date(year, 1, 1)
        jan1_ordinal = jan1.toordinal()
        jan1_weekday = jan1.weekday()
        week1_start_ordinal = jan1_ordinal - ((jan1_weekday + 1) % 7)
        return week1_start_ordinal
    
    >>> from datetime import date
    >>> week_from_date(date(2014, 12, 29))
    (2015, 1)
    
  • MMWR (CDC): First week starts with Sunday and must contain the January 4th. I created the epiweeks package specifically for this numbering system (also has support for the ISO system). Here is an example:
    >>> from datetime import date
    >>> from epiweeks import Week
    >>> Week.fromdate(date(2014, 12, 29))
    (2014, 53)
    

回答 8

如果您仅使用等周日历号,则以下内容就足够了:

import datetime
week = date(year=2014, month=1, day=1).isocalendar()[1]

这将检索isocalendar返回的元组的第二个成员,作为我们的星期数。

但是,如果您要使用公历中处理的日期函数,则仅等距日历无法正常工作!请看以下示例:

import datetime
date = datetime.datetime.strptime("2014-1-1", "%Y-%W-%w")
week = date.isocalendar()[1]

此处的字符串表示返回2014年第一周的星期一作为我们的日期。当我们使用isocalendar在此处检索星期数时,我们希望可以返回相同的星期数,但事实并非如此。相反,我们得到的周数为2。为什么?

阳历的第一周是包含星期一的第一周。等值线的第1周是包含星期四的第一周。2014年初的不完整一周包含一个星期四,因此这是等距日历的第1周,date第2周。

如果要获得公历周,我们将需要从等距转换为公历。这是个简单的功能,可以解决问题。

import datetime

def gregorian_week(date):
    # The isocalendar week for this date
    iso_week = date.isocalendar()[1]

    # The baseline Gregorian date for the beginning of our date's year
    base_greg = datetime.datetime.strptime('%d-1-1' % date.year, "%Y-%W-%w")

    # If the isocalendar week for this date is not 1, we need to 
    # decrement the iso_week by 1 to get the Gregorian week number
    return iso_week if base_greg.isocalendar()[1] == 1 else iso_week - 1

If you are only using the isocalendar week number across the board the following should be sufficient:

import datetime
week = date(year=2014, month=1, day=1).isocalendar()[1]

This retrieves the second member of the tuple returned by isocalendar for our week number.

However, if you are going to be using date functions that deal in the Gregorian calendar, isocalendar alone will not work! Take the following example:

import datetime
date = datetime.datetime.strptime("2014-1-1", "%Y-%W-%w")
week = date.isocalendar()[1]

The string here says to return the Monday of the first week in 2014 as our date. When we use isocalendar to retrieve the week number here, we would expect to get the same week number back, but we don’t. Instead we get a week number of 2. Why?

Week 1 in the Gregorian calendar is the first week containing a Monday. Week 1 in the isocalendar is the first week containing a Thursday. The partial week at the beginning of 2014 contains a Thursday, so this is week 1 by the isocalendar, and making date week 2.

If we want to get the Gregorian week, we will need to convert from the isocalendar to the Gregorian. Here is a simple function that does the trick.

import datetime

def gregorian_week(date):
    # The isocalendar week for this date
    iso_week = date.isocalendar()[1]

    # The baseline Gregorian date for the beginning of our date's year
    base_greg = datetime.datetime.strptime('%d-1-1' % date.year, "%Y-%W-%w")

    # If the isocalendar week for this date is not 1, we need to 
    # decrement the iso_week by 1 to get the Gregorian week number
    return iso_week if base_greg.isocalendar()[1] == 1 else iso_week - 1

回答 9

您可以尝试使用%W指令,如下所示:

d = datetime.datetime.strptime('2016-06-16','%Y-%m-%d')
print(datetime.datetime.strftime(d,'%W'))

‘%W’:一年中的第几周(星期一为一周的第一天),以十进制数表示。第一个星期一之前的新的一年中的所有天都视为在第0周。(00,01,…,53)

You can try %W directive as below:

d = datetime.datetime.strptime('2016-06-16','%Y-%m-%d')
print(datetime.datetime.strftime(d,'%W'))

‘%W’: Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. (00, 01, …, 53)


回答 10

isocalendar()返回某些日期的不正确的年和周数值:

Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime as dt
>>> myDateTime = dt.datetime.strptime("20141229T000000.000Z",'%Y%m%dT%H%M%S.%fZ')
>>> yr,weekNumber,weekDay = myDateTime.isocalendar()
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2015, weekNumber is 1

与Mark Ransom的方法进行比较:

>>> yr = myDateTime.year
>>> weekNumber = ((myDateTime - dt.datetime(yr,1,1)).days/7) + 1
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2014, weekNumber is 52

isocalendar() returns incorrect year and weeknumber values for some dates:

Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime as dt
>>> myDateTime = dt.datetime.strptime("20141229T000000.000Z",'%Y%m%dT%H%M%S.%fZ')
>>> yr,weekNumber,weekDay = myDateTime.isocalendar()
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2015, weekNumber is 1

Compare with Mark Ransom’s approach:

>>> yr = myDateTime.year
>>> weekNumber = ((myDateTime - dt.datetime(yr,1,1)).days/7) + 1
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2014, weekNumber is 52

回答 11

我将讨论概括为两个步骤:

  1. 将原始格式转换为datetime对象。
  2. 使用datetime对象或date对象的功能来计算星期数。

暖身

python

from datetime import datetime, date, time
d = date(2005, 7, 14)
t = time(12, 30)
dt = datetime.combine(d, t)
print(dt)

“`

第一步

要手动生成datetime对象,我们可以使用datetime.datetime(2017,5,3)datetime.datetime.now()

但是实际上,我们通常需要解析一个现有的字符串。我们可以使用strptime函数,例如datetime.strptime('2017-5-3','%Y-%m-%d')您必须指定的格式。有关不同格式代码的详细信息,请参见官方文档中

或者,更方便的方法是使用dateparse模块。例子有dateparser.parse('16 Jun 2010')dateparser.parse('12/2/12')dateparser.parse('2017-5-3')

以上两种方法将返回一个datetime对象。

第二步

使用获得的 datetime对象进行调用strptime(format)。例如,

python

dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object. This day is Sunday
print(dt.strftime("%W")) # '00' Monday as the 1st day of the week. All days in a new year preceding the 1st Monday are considered to be in week 0.
print(dt.strftime("%U")) # '01' Sunday as the 1st day of the week. All days in a new year preceding the 1st Sunday are considered to be in week 0.
print(dt.strftime("%V")) # '52' Monday as the 1st day of the week. Week 01 is the week containing Jan 4.

“`

决定使用哪种格式是非常棘手的。更好的方法是获取date对象进行调用isocalendar()。例如,

python

dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object
d = dt.date() # convert to a date object. equivalent to d = date(2017,1,1), but date.strptime() don't have the parse function
year, week, weekday = d.isocalendar() 
print(year, week, weekday) # (2016,52,7) in the ISO standard

“`

实际上,您将更有可能用来date.isocalendar()编写每周报告,尤其是在“圣诞节-新年”购物季节。

I summarize the discussion to two steps:

  1. Convert the raw format to a datetime object.
  2. Use the function of a datetime object or a date object to calculate the week number.

Warm up

“`python

from datetime import datetime, date, time
d = date(2005, 7, 14)
t = time(12, 30)
dt = datetime.combine(d, t)
print(dt)

“`

1st step

To manually generate a datetime object, we can use datetime.datetime(2017,5,3) or datetime.datetime.now().

But in reality, we usually need to parse an existing string. we can use strptime function, such as datetime.strptime('2017-5-3','%Y-%m-%d') in which you have to specific the format. Detail of different format code can be found in the official documentation.

Alternatively, a more convenient way is to use dateparse module. Examples are dateparser.parse('16 Jun 2010'), dateparser.parse('12/2/12') or dateparser.parse('2017-5-3')

The above two approaches will return a datetime object.

2nd step

Use the obtained datetime object to call strptime(format). For example,

“`python

dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object. This day is Sunday
print(dt.strftime("%W")) # '00' Monday as the 1st day of the week. All days in a new year preceding the 1st Monday are considered to be in week 0.
print(dt.strftime("%U")) # '01' Sunday as the 1st day of the week. All days in a new year preceding the 1st Sunday are considered to be in week 0.
print(dt.strftime("%V")) # '52' Monday as the 1st day of the week. Week 01 is the week containing Jan 4.

“`

It’s very tricky to decide which format to use. A better way is to get a date object to call isocalendar(). For example,

“`python

dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object
d = dt.date() # convert to a date object. equivalent to d = date(2017,1,1), but date.strptime() don't have the parse function
year, week, weekday = d.isocalendar() 
print(year, week, weekday) # (2016,52,7) in the ISO standard

“`

In reality, you will be more likely to use date.isocalendar() to prepare a weekly report, especially in the “Christmas-New Year” shopping season.


回答 12

userInput = input ("Please enter project deadline date (dd/mm/yyyy/): ")

import datetime

currentDate = datetime.datetime.today()

testVar = datetime.datetime.strptime(userInput ,"%d/%b/%Y").date()

remainDays = testVar - currentDate.date()

remainWeeks = (remainDays.days / 7.0) + 1


print ("Please pay attention for deadline of project X in days and weeks are  : " ,(remainDays) , "and" ,(remainWeeks) , "Weeks ,\nSo  hurryup.............!!!") 
userInput = input ("Please enter project deadline date (dd/mm/yyyy/): ")

import datetime

currentDate = datetime.datetime.today()

testVar = datetime.datetime.strptime(userInput ,"%d/%b/%Y").date()

remainDays = testVar - currentDate.date()

remainWeeks = (remainDays.days / 7.0) + 1


print ("Please pay attention for deadline of project X in days and weeks are  : " ,(remainDays) , "and" ,(remainWeeks) , "Weeks ,\nSo  hurryup.............!!!") 

回答 13

已经给出了很多答案,但是id喜欢添加到它们中。

如果您需要将星期显示为年/周样式(例如1953年-2019年第53周,2001年-2020年第1周等),则可以执行以下操作:

import datetime

year = datetime.datetime.now()
week_num = datetime.date(year.year, year.month, year.day).strftime("%V")
long_week_num = str(year.year)[0:2] + str(week_num)

这将需要当前的年和周,而在撰写本文时,long_week_num将是:

>>> 2006

A lot of answers have been given, but id like to add to them.

If you need the week to display as a year/week style (ex. 1953 – week 53 of 2019, 2001 – week 1 of 2020 etc.), you can do this:

import datetime

year = datetime.datetime.now()
week_num = datetime.date(year.year, year.month, year.day).strftime("%V")
long_week_num = str(year.year)[0:2] + str(week_num)

It will take the current year and week, and long_week_num in the day of writing this will be:

>>> 2006

Python中的ISO时间(ISO 8601)

问题:Python中的ISO时间(ISO 8601)

我有一个档案。在Python中,我想保留其创建时间,并将其转换为ISO时间(ISO 8601)字符串, 同时保留它是在东部时区(ET)创建的事实

如何获取文件的ctime并将其转换为表示东部时区的ISO时间字符串(并在必要时考虑夏令时)?

I have a file. In Python, I would like to take its creation time, and convert it to an ISO time (ISO 8601) string while preserving the fact that it was created in the Eastern Time Zone (ET).

How do I take the file’s ctime and convert it to an ISO time string that indicates the Eastern Time Zone (and takes into account daylight savings time, if necessary)?


回答 0

ISO 8601的本地:

import datetime
datetime.datetime.now().isoformat()
>>> 2020-03-20T14:28:23.382748

UTC符合ISO 8601:

import datetime
datetime.datetime.utcnow().isoformat()
>>> 2020-03-20T01:30:08.180856

ISO 8601本地,无微秒:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:30:43

具有TimeZone信息的UTC到ISO 8601(Python 3):

import datetime
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
>>> 2020-03-20T01:31:12.467113+00:00

UTC到ISO 8601,具有本地时区信息,无微秒(Python 3):

import datetime
datetime.datetime.now().astimezone().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:31:43+13:00

具有TimeZone信息的ISO 8601本地(Python 3):

import datetime
datetime.datetime.now().astimezone().isoformat()
>>> 2020-03-20T14:32:16.458361+13:00

注意astimezone()在utc时间使用时有一个错误。这给出了错误的结果:

datetime.datetime.utcnow().astimezone().isoformat() #Incorrect result

对于Python 2,请参阅并使用pytz

Local to ISO 8601:

import datetime
datetime.datetime.now().isoformat()
>>> 2020-03-20T14:28:23.382748

UTC to ISO 8601:

import datetime
datetime.datetime.utcnow().isoformat()
>>> 2020-03-20T01:30:08.180856

Local to ISO 8601 without microsecond:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:30:43

UTC to ISO 8601 with TimeZone information (Python 3):

import datetime
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
>>> 2020-03-20T01:31:12.467113+00:00

UTC to ISO 8601 with Local TimeZone information without microsecond (Python 3):

import datetime
datetime.datetime.now().astimezone().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:31:43+13:00

Local to ISO 8601 with TimeZone information (Python 3):

import datetime
datetime.datetime.now().astimezone().isoformat()
>>> 2020-03-20T14:32:16.458361+13:00

Notice there is a bug when using astimezone() on utc time. This gives an incorrect result:

datetime.datetime.utcnow().astimezone().isoformat() #Incorrect result

For Python 2, see and use pytz.


回答 1

这是我用来转换为XSD日期时间格式的方法:

from datetime import datetime
datetime.now().replace(microsecond=0).isoformat()
# You get your ISO string

我在寻找XSD日期时间格式(xs:dateTime)时遇到了这个问题。我需要从中删除微秒isoformat

Here is what I use to convert to the XSD datetime format:

from datetime import datetime
datetime.now().replace(microsecond=0).isoformat()
# You get your ISO string

I came across this question when looking for the XSD date time format (xs:dateTime). I needed to remove the microseconds from isoformat.


回答 2

ISO 8601时间表示

国际标准ISO 8601描述了日期和时间的字符串表示形式。此格式的两个简单示例是

2010-12-16 17:22:15
20101216T172215

(都代表2010年12月16日),但是该格式还允许亚秒级的解析时间并指定时区。这种格式当然不是特定于Python的,但是它对于以可移植格式存储日期和时间很有用。有关此格式的详细信息,请参见Markus Kuhn条目

我建议使用这种格式在文件中存储时间。

获取此表示形式中的当前时间的一种方法是使用Python标准库中时间模块中的strftime:

>>> from time import strftime
>>> strftime("%Y-%m-%d %H:%M:%S")
'2010-03-03 21:16:45'

您可以使用datetime类的strptime构造函数:

>>> from datetime import datetime
>>> datetime.strptime("2010-06-04 21:08:12", "%Y-%m-%d %H:%M:%S")
datetime.datetime(2010, 6, 4, 21, 8, 12)

最强大的是Egenix mxDateTime模块:

>>> from mx.DateTime.ISO import ParseDateTimeUTC
>>> from datetime import datetime
>>> x = ParseDateTimeUTC("2010-06-04 21:08:12")
>>> datetime.fromtimestamp(x)
datetime.datetime(2010, 3, 6, 21, 8, 12)

参考文献

ISO 8601 Time Representation

The international standard ISO 8601 describes a string representation for dates and times. Two simple examples of this format are

2010-12-16 17:22:15
20101216T172215

(which both stand for the 16th of December 2010), but the format also allows for sub-second resolution times and to specify time zones. This format is of course not Python-specific, but it is good for storing dates and times in a portable format. Details about this format can be found in the Markus Kuhn entry.

I recommend use of this format to store times in files.

One way to get the current time in this representation is to use strftime from the time module in the Python standard library:

>>> from time import strftime
>>> strftime("%Y-%m-%d %H:%M:%S")
'2010-03-03 21:16:45'

You can use the strptime constructor of the datetime class:

>>> from datetime import datetime
>>> datetime.strptime("2010-06-04 21:08:12", "%Y-%m-%d %H:%M:%S")
datetime.datetime(2010, 6, 4, 21, 8, 12)

The most robust is the Egenix mxDateTime module:

>>> from mx.DateTime.ISO import ParseDateTimeUTC
>>> from datetime import datetime
>>> x = ParseDateTimeUTC("2010-06-04 21:08:12")
>>> datetime.fromtimestamp(x)
datetime.datetime(2010, 3, 6, 21, 8, 12)

References


回答 3

我在文档中找到了datetime.isoformat 。它似乎可以满足您的要求:

datetime.isoformat([sep])

Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DDTHH:MM:SS

If utcoffset() does not return None, a 6-character string is appended, giving the UTC offset in (signed) hours and minutes: YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if microsecond is 0 YYYY-MM-DDTHH:MM:SS+HH:MM

The optional argument sep (default 'T') is a one-character separator, placed between the date and time portions of the result. For example,
>>>

>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
...     def utcoffset(self, dt): return timedelta(minutes=-399)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'

I found the datetime.isoformat in the documentation. It seems to do what you want:

datetime.isoformat([sep])

Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DDTHH:MM:SS

If utcoffset() does not return None, a 6-character string is appended, giving the UTC offset in (signed) hours and minutes: YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if microsecond is 0 YYYY-MM-DDTHH:MM:SS+HH:MM

The optional argument sep (default 'T') is a one-character separator, placed between the date and time portions of the result. For example,
>>>

>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
...     def utcoffset(self, dt): return timedelta(minutes=-399)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'

回答 4

ISO 8601允许紧凑的表示形式,除了之外没有任何分隔符T,所以我喜欢使用这种单线来获得快速的时间戳字符串:

>>> datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%S.%fZ")
'20180905T140903.591680Z'

如果您不需要微秒,则只需忽略以下.%f部分:

>>> datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
'20180905T140903Z'

对于当地时间:

>>> datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
'20180905T140903'

编辑:

阅读更多内容后,建议您不要使用标点符号。RFC3339建议使用这种样式,因为如果每个人都使用标点符号,则不会有多个ISO 8601字符串按标点符号分组的风险。因此,符合要求的字符串的一个衬里是:

>>> datetime.datetime.now().strftime("%Y-%m-%dT%H:%M%SZ")
'2018-09-05T14:09:03Z'

ISO 8601 allows a compact representation with no separators except for the T, so I like to use this one-liner to get a quick timestamp string:

>>> datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%S.%fZ")
'20180905T140903.591680Z'

If you don’t need the microseconds, just leave out the .%f part:

>>> datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
'20180905T140903Z'

For local time:

>>> datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
'20180905T140903'

Edit:

After reading up on this some more, I recommend you leave the punctuation in. RFC 3339 recommends that style because if everyone uses punctuation, there isn’t a risk of things like multiple ISO 8601 strings being sorted in groups on their punctuation. So the one liner for a compliant string would be:

>>> datetime.datetime.now().strftime("%Y-%m-%dT%H:%M%SZ")
'2018-09-05T14:09:03Z'

回答 5

ISO 8601时的格式不存储时区的名称,只有相应的UTC偏移被保留。

要将文件ctime转换为ISO 8601时间字符串,同时在Python中保留UTC偏移量3:

>>> import os
>>> from datetime import datetime, timezone
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, timezone.utc)
>>> dt.astimezone().isoformat()
'2015-11-27T00:29:06.839600-05:00'

该代码假定您的本地时区为 东部时区(ET),并且系统为给定的POSIX时间戳(ts)提供了正确的UTC偏移,即Python可以访问您系统上的历史时区数据库或该时区具有在给定日期使用相同的规则。

如果您需要便携式解决方案;使用pytz提供访问tz数据库模块

>>> import os
>>> from datetime import datetime
>>> import pytz  # pip install pytz
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, pytz.timezone('America/New_York'))
>>> dt.isoformat()
'2015-11-27T00:29:06.839600-05:00'

在这种情况下,结果是相同的。

如果您需要时区名称/缩写/时区ID,请分别存储。

>>> dt.astimezone().strftime('%Y-%m-%d %H:%M:%S%z (%Z)')
'2015-11-27 00:29:06-0500 (EST)'

注意:不能,:在UTC偏移量和EST时区中,缩写不是ISO 8601时间格式的一部分。它不是唯一的。

同一库的不同库/不同版本可能对同一日期/时区使用不同的时区规则。如果是将来的日期,那么规则可能还未知。换句话说,根据您使用的规则,相同的UTC时间可能对应于不同的本地时间-以ISO 8601格式保存时间可以保留UTC时间,并且本地时间与平台上使用的当前时区规则相对应。如果规则不同,则可能需要在其他平台上重新计算本地时间。

The ISO 8601 time format does not store a time zone name, only the corresponding UTC offset is preserved.

To convert a file ctime to an ISO 8601 time string while preserving the UTC offset in Python 3:

>>> import os
>>> from datetime import datetime, timezone
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, timezone.utc)
>>> dt.astimezone().isoformat()
'2015-11-27T00:29:06.839600-05:00'

The code assumes that your local timezone is Eastern Time Zone (ET) and that your system provides a correct UTC offset for the given POSIX timestamp (ts), i.e., Python has access to a historical timezone database on your system or the time zone had the same rules at a given date.

If you need a portable solution; use the pytz module that provides access to the tz database:

>>> import os
>>> from datetime import datetime
>>> import pytz  # pip install pytz
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, pytz.timezone('America/New_York'))
>>> dt.isoformat()
'2015-11-27T00:29:06.839600-05:00'

The result is the same in this case.

If you need the time zone name/abbreviation/zone id, store it separately.

>>> dt.astimezone().strftime('%Y-%m-%d %H:%M:%S%z (%Z)')
'2015-11-27 00:29:06-0500 (EST)'

Note: no, : in the UTC offset and EST timezone abbreviation is not part of the ISO 8601 time format. It is not unique.

Different libraries/different versions of the same library may use different time zone rules for the same date/timezone. If it is a future date then the rules might be unknown yet. In other words, the same UTC time may correspond to a different local time depending on what rules you use — saving a time in ISO 8601 format preserves UTC time and the local time that corresponds to the current time zone rules in use on your platform. You might need to recalculate the local time on a different platform if it has different rules.


回答 6

您需要使用os.stat来获取文件创建时间,并结合使用time.strftimetime.timezone进行格式化:

>>> import time
>>> import os
>>> t = os.stat('C:/Path/To/File.txt').st_ctime
>>> t = time.localtime(t)
>>> formatted = time.strftime('%Y-%m-%d %H:%M:%S', t)
>>> tz = str.format('{0:+06.2f}', float(time.timezone) / 3600)
>>> final = formatted + tz
>>> 
>>> final
'2008-11-24 14:46:08-02.00'

You’ll need to use os.stat to get the file creation time and a combination of time.strftime and time.timezone for formatting:

>>> import time
>>> import os
>>> t = os.stat('C:/Path/To/File.txt').st_ctime
>>> t = time.localtime(t)
>>> formatted = time.strftime('%Y-%m-%d %H:%M:%S', t)
>>> tz = str.format('{0:+06.2f}', float(time.timezone) / 3600)
>>> final = formatted + tz
>>> 
>>> final
'2008-11-24 14:46:08-02.00'

回答 7

如果我错了(不是),请纠正我,但是与UTC的偏差会随着夏时制而变化。所以你应该使用

tz = str.format('{0:+06.2f}', float(time.altzone) / 3600)

我还认为该标志应有所不同:

tz = str.format('{0:+06.2f}', -float(time.altzone) / 3600)

我可能是错的,但我不这么认为。

Correct me if I’m wrong (I’m not), but the offset from UTC changes with daylight saving time. So you should use

tz = str.format('{0:+06.2f}', float(time.altzone) / 3600)

I also believe that the sign should be different:

tz = str.format('{0:+06.2f}', -float(time.altzone) / 3600)

I could be wrong, but I don’t think so.


回答 8

我同意Jarek的观点,并且还要注意ISO偏移分隔符是冒号,因此我认为最终答案应该是:

isodate.datetime_isoformat(datetime.datetime.now()) + str.format('{0:+06.2f}', -float(time.timezone) / 3600).replace('.', ':')

I agree with Jarek, and I furthermore note that the ISO offset separator character is a colon, so I think the final answer should be:

isodate.datetime_isoformat(datetime.datetime.now()) + str.format('{0:+06.2f}', -float(time.timezone) / 3600).replace('.', ':')

回答 9

在estani的出色回答中添加了一个小的变化

具有TimeZone且没有微秒信息(Python 3)的ISO 8601本地:

import datetime, time

utc_offset_sec = time.altzone if time.localtime().tm_isdst else time.timezone
utc_offset = datetime.timedelta(seconds=-utc_offset_sec)
datetime.datetime.now().replace(microsecond=0, tzinfo=datetime.timezone(offset=utc_offset)).isoformat()

样本输出:

'2019-11-06T12:12:06-08:00'

测试了此输出可以同时被Javascript Date和C#解析DateTime/DateTimeOffset

Adding a small variation to estani’s excellent answer

Local to ISO 8601 with TimeZone and no microsecond info (Python 3):

import datetime, time

utc_offset_sec = time.altzone if time.localtime().tm_isdst else time.timezone
utc_offset = datetime.timedelta(seconds=-utc_offset_sec)
datetime.datetime.now().replace(microsecond=0, tzinfo=datetime.timezone(offset=utc_offset)).isoformat()

Sample Output:

'2019-11-06T12:12:06-08:00'

Tested that this output can be parsed by both Javascript Date and C# DateTime/DateTimeOffset


回答 10

我开发了此功能:

def iso_8601_format(dt):
    """YYYY-MM-DDThh:mm:ssTZD (1997-07-16T19:20:30-03:00)"""

    if dt is None:
        return ""

    fmt_datetime = dt.strftime('%Y-%m-%dT%H:%M:%S')
    tz = dt.utcoffset()
    if tz is None:
        fmt_timezone = "+00:00"
    else:
        fmt_timezone = str.format('{0:+06.2f}', float(tz.total_seconds() / 3600))

    return fmt_datetime + fmt_timezone

I’ve developed this function:

def iso_8601_format(dt):
    """YYYY-MM-DDThh:mm:ssTZD (1997-07-16T19:20:30-03:00)"""

    if dt is None:
        return ""

    fmt_datetime = dt.strftime('%Y-%m-%dT%H:%M:%S')
    tz = dt.utcoffset()
    if tz is None:
        fmt_timezone = "+00:00"
    else:
        fmt_timezone = str.format('{0:+06.2f}', float(tz.total_seconds() / 3600))

    return fmt_datetime + fmt_timezone

回答 11

import datetime, time    
def convert_enddate_to_seconds(self, ts):
    """Takes ISO 8601 format(string) and converts into epoch time."""
     dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
                datetime.timedelta(hours=int(ts[-5:-3]),
                minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
    seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
    return seconds 

>>> import datetime, time
>>> ts = '2012-09-30T15:31:50.262-08:00'
>>> dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
>>> seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
>>> seconds
1348990310.26
import datetime, time    
def convert_enddate_to_seconds(self, ts):
    """Takes ISO 8601 format(string) and converts into epoch time."""
     dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
                datetime.timedelta(hours=int(ts[-5:-3]),
                minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
    seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
    return seconds 

>>> import datetime, time
>>> ts = '2012-09-30T15:31:50.262-08:00'
>>> dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
>>> seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
>>> seconds
1348990310.26

在Python中以YYYY-MM-DD获取今天的日期?

问题:在Python中以YYYY-MM-DD获取今天的日期?

我在用着:

str(datetime.datetime.today()).split()[0]

YYYY-MM-DD格式返回今天的日期。

有没有那么简单的方法可以做到这一点?

I’m using:

str(datetime.datetime.today()).split()[0]

to return today’s date in the YYYY-MM-DD format.

Is there a less crude way to achieve this?


回答 0

您可以使用strftime

from datetime import datetime

datetime.today().strftime('%Y-%m-%d')

此外,对于任何还在末尾寻找零填充的小时,分​​钟和秒的人:(Gabriel Staples评论)

datetime.today().strftime('%Y-%m-%d-%H:%M:%S')

You can use strftime:

from datetime import datetime

datetime.today().strftime('%Y-%m-%d')

Additionally, for anyone also looking for a zero-padded Hour, Minute, and Second at the end: (Comment by Gabriel Staples)

datetime.today().strftime('%Y-%m-%d-%H:%M:%S')

回答 1

您可以使用datetime.date.today()并将结果datetime.date对象转换为字符串:

from datetime import date
today = str(date.today())
print(today)   # '2017-12-26'

You can use datetime.date.today() and convert the resulting datetime.date object to a string:

from datetime import date
today = str(date.today())
print(today)   # '2017-12-26'

回答 2

如果您想记住有趣的代码,那么日期时间就是很好的选择。您不喜欢简单吗?

>>> import arrow
>>> arrow.now().format('YYYY-MM-DD')
'2017-02-17'

这个模块足够聪明,可以理解您的意思

做吧pip install arrow

附录:在回答那些对此练习感到困惑的人时,我只想说箭头代表了Python处理日期的另一种方法。这主要是我的建议。

Datetime is just lovely if you like remembering funny codes. Wouldn’t you prefer simplicity?

>>> import arrow
>>> arrow.now().format('YYYY-MM-DD')
'2017-02-17'

This module is clever enough to understand what you mean.

Just do pip install arrow.

Addendum: In answer to those who become exercised over this answer let me just say that arrow represents one of the alternative approaches to dealing with dates in Python. That’s mostly what I meant to suggest.


回答 3

我总是isoformat()为此使用功能。

from datetime import date    
today = date.today().isoformat()
print(today) # '2018-12-05'

请注意,如果您还需要标准格式的时间,则此方法也适用于datetime对象。

from datetime import datetime
now = datetime.today().isoformat()
print(now) # '2018-12-05T11:15:55.126382'

I always use the isoformat() function for this.

from datetime import date    
today = date.today().isoformat()
print(today) # '2018-12-05'

Note that this also works on datetime objects if you need the time in standard format as well.

from datetime import datetime
now = datetime.today().isoformat()
print(now) # '2018-12-05T11:15:55.126382'

回答 4

其他答案建议使用python datetime.datetime,但是正如@Bill Bell所说,还有其他库提供了更简单的datetime接口,这些接口既可以作为服务,也可以作为更大的API生态系统的一部分。这里有两个这样的库使工作变得datetimes非常简单。

潘达斯

您可以pd.to_datetimepandas库中使用。这里有各种选项,具体取决于您要返回的内容。

import pandas as pd

pd.to_datetime('today')  # pd.to_datetime('now')
# Timestamp('2019-03-27 00:00:10.958567')

作为python datetime对象,

pd.to_datetime('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 50, 42, 587629)

作为格式化的日期字符串,

pd.to_datetime('today').isoformat()
# '2019-04-18T04:03:32.493337'

# Or, `strftime` for custom formats.
pd.to_datetime('today').strftime('%Y-%m-%d')
# '2019-03-27'

要仅从时间戳记中获取日期,请调用Timestamp.date

pd.to_datetime('today').date()
# datetime.date(2019, 3, 27)

除了之外to_datetime,您还可以Timestamp使用实例化对象,

pd.Timestamp('today')  # pd.Timestamp('now')
# Timestamp('2019-04-18 03:43:33.233093')

pd.Timestamp('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 53, 46, 220068)

如果要使您的时间戳记时区知道,请将时区传递给tz参数。

pd.Timestamp('now', tz='America/Los_Angeles')
# Timestamp('2019-04-18 03:59:02.647819-0700', tz='America/Los_Angeles')

如果您使用摆锤,则有一些有趣的选择。您可以使用来获取当前时间戳记now()或使用来获取今天的日期today()

import pendulum 

pendulum.now()
# DateTime(2019, 3, 27, 0, 2, 41, 452264, tzinfo=Timezone('America/Los_Angeles'))

pendulum.today()
# DateTime(2019, 3, 27, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

此外,您也可以直接获取tomorrow()yesterday()的日期,而无需执行任何其他的timedelta算法。

pendulum.yesterday()
# DateTime(2019, 3, 26, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

pendulum.tomorrow()
# DateTime(2019, 3, 28, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

有各种可用的格式设置选项。

pendulum.now().to_date_string()
# '2019-03-27'

pendulum.now().to_formatted_date_string()
# 'Mar 27, 2019'

pendulum.now().to_day_datetime_string()
# 'Wed, Mar 27, 2019 12:04 AM'

Other answers suggest the use of python’s datetime.datetime, but as @Bill Bell said, there are other libraries that offer simpler datetime interfaces either as a service or as part of a larger ecosystem of APIs. Here are two such libraries that make working with datetimes very simple.

PANDAS

You can use pd.to_datetime from the pandas library. Here are various options, depending on what you want returned.

import pandas as pd

pd.to_datetime('today')  # pd.to_datetime('now')
# Timestamp('2019-03-27 00:00:10.958567')

As a python datetime object,

pd.to_datetime('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 50, 42, 587629)

As a formatted date string,

pd.to_datetime('today').isoformat()
# '2019-04-18T04:03:32.493337'

# Or, `strftime` for custom formats.
pd.to_datetime('today').strftime('%Y-%m-%d')
# '2019-03-27'

To get just the date from the timestamp, call Timestamp.date.

pd.to_datetime('today').date()
# datetime.date(2019, 3, 27)

Aside from to_datetime, you can directly instantiate a Timestamp object using,

pd.Timestamp('today')  # pd.Timestamp('now')
# Timestamp('2019-04-18 03:43:33.233093')

pd.Timestamp('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 53, 46, 220068)

If you want to make your Timestamp timezone aware, pass a timezone to the tz argument.

pd.Timestamp('now', tz='America/Los_Angeles')
# Timestamp('2019-04-18 03:59:02.647819-0700', tz='America/Los_Angeles')

PENDULUM

If you’re working with pendulum, there are some interesting choices. You can get the current timestamp using now() or today’s date using today().

import pendulum 

pendulum.now()
# DateTime(2019, 3, 27, 0, 2, 41, 452264, tzinfo=Timezone('America/Los_Angeles'))

pendulum.today()
# DateTime(2019, 3, 27, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

Additionally, you can also get tomorrow() or yesterday()‘s date directly without having to do any additional timedelta arithmetic.

pendulum.yesterday()
# DateTime(2019, 3, 26, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

pendulum.tomorrow()
# DateTime(2019, 3, 28, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

There are various formatting options available.

pendulum.now().to_date_string()
# '2019-03-27'

pendulum.now().to_formatted_date_string()
# 'Mar 27, 2019'

pendulum.now().to_day_datetime_string()
# 'Wed, Mar 27, 2019 12:04 AM'

回答 5

答案很晚,但是您可以使用:

import time
today = time.strftime("%Y-%m-%d")
# 2020-02-14

Very late answer, but you can use:

import time
today = time.strftime("%Y-%m-%d")
# 2020-02-14

回答 6

您可以使用,

>>> from datetime import date
>>> date.today().__str__()
'2019-10-05'

You can use,

>>> from datetime import date
>>> date.today().__str__()
'2019-10-05'

回答 7

我喜欢这个,因为这很简单,但是可能效率不高且有问题。如果您要一个高度防错的程序,则必须检查shell命令的退出代码。

os.system('date +%Y-%m-%d')

I prefer this, because this is simple, but maybe somehow inefficient and buggy. You must check the exit code of shell command if you want a strongly error-proof program.

os.system('date +%Y-%m-%d')

在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

如何获得给定日期的星期几?

问题:如何获得给定日期的星期几?

我想找出以下内容:给定日期(datetime对象),星期几是几号?

例如,星期日是第一天,星期一:第二天..依此类推

然后,如果输入的内容类似于今天的日期。

>>> today = datetime.datetime(2017, 10, 20)
>>> today.get_weekday()  # what I look for

输出可能是6(因为它是星期五)

I want to find out the following: given a date (datetime object), what is the corresponding day of the week?

For instance, Sunday is the first day, Monday: second day.. and so on

And then if the input is something like today’s date.

Example

>>> today = datetime.datetime(2017, 10, 20)
>>> today.get_weekday()  # what I look for

The output is maybe 6 (since it’s Friday)


回答 0

使用weekday()docs):

>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2012, 3, 23, 23, 24, 55, 173504)
>>> datetime.datetime.today().weekday()
4

从文档中:

以整数形式返回星期几,其中星期一为0,星期日为6。

Use weekday() (docs):

>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2012, 3, 23, 23, 24, 55, 173504)
>>> datetime.datetime.today().weekday()
4

From the documentation:

Return the day of the week as an integer, where Monday is 0 and Sunday is 6.


回答 1

如果您想用英文注明日期:

from datetime import date
import calendar
my_date = date.today()
calendar.day_name[my_date.weekday()]  #'Wednesday'

If you’d like to have the date in English:

from datetime import date
import calendar
my_date = date.today()
calendar.day_name[my_date.weekday()]  #'Wednesday'

回答 2

如果您想用英文注明日期:

>>> from datetime import datetime
>>> datetime.today().strftime('%A')
'Wednesday'

了解更多:https//docs.python.org/2/library/datetime.html#strftime-strptime-behavior

If you’d like to have the date in English:

>>> from datetime import datetime
>>> datetime.today().strftime('%A')
'Wednesday'

Read more: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior


回答 3


回答 4

我解决了CodeChef 问题

import datetime
dt = '21/03/2012'
day, month, year = (int(x) for x in dt.split('/'))    
ans = datetime.date(year, month, day)
print (ans.strftime("%A"))

I solved this for a CodeChef question.

import datetime
dt = '21/03/2012'
day, month, year = (int(x) for x in dt.split('/'))    
ans = datetime.date(year, month, day)
print (ans.strftime("%A"))

回答 5

没有导入日期为1700/1/1之后的解决方案

def weekDay(year, month, day):
    offset = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
    week   = ['Sunday', 
              'Monday', 
              'Tuesday', 
              'Wednesday', 
              'Thursday',  
              'Friday', 
              'Saturday']
    afterFeb = 1
    if month > 2: afterFeb = 0
    aux = year - 1700 - afterFeb
    # dayOfWeek for 1700/1/1 = 5, Friday
    dayOfWeek  = 5
    # partial sum of days betweem current date and 1700/1/1
    dayOfWeek += (aux + afterFeb) * 365                  
    # leap year correction    
    dayOfWeek += aux / 4 - aux / 100 + (aux + 100) / 400     
    # sum monthly and day offsets
    dayOfWeek += offset[month - 1] + (day - 1)               
    dayOfWeek %= 7
    return dayOfWeek, week[dayOfWeek]

print weekDay(2013, 6, 15) == (6, 'Saturday')
print weekDay(1969, 7, 20) == (0, 'Sunday')
print weekDay(1945, 4, 30) == (1, 'Monday')
print weekDay(1900, 1, 1)  == (1, 'Monday')
print weekDay(1789, 7, 14) == (2, 'Tuesday')

A solution whithout imports for dates after 1700/1/1

def weekDay(year, month, day):
    offset = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
    week   = ['Sunday', 
              'Monday', 
              'Tuesday', 
              'Wednesday', 
              'Thursday',  
              'Friday', 
              'Saturday']
    afterFeb = 1
    if month > 2: afterFeb = 0
    aux = year - 1700 - afterFeb
    # dayOfWeek for 1700/1/1 = 5, Friday
    dayOfWeek  = 5
    # partial sum of days betweem current date and 1700/1/1
    dayOfWeek += (aux + afterFeb) * 365                  
    # leap year correction    
    dayOfWeek += aux / 4 - aux / 100 + (aux + 100) / 400     
    # sum monthly and day offsets
    dayOfWeek += offset[month - 1] + (day - 1)               
    dayOfWeek %= 7
    return dayOfWeek, week[dayOfWeek]

print weekDay(2013, 6, 15) == (6, 'Saturday')
print weekDay(1969, 7, 20) == (0, 'Sunday')
print weekDay(1945, 4, 30) == (1, 'Monday')
print weekDay(1900, 1, 1)  == (1, 'Monday')
print weekDay(1789, 7, 14) == (2, 'Tuesday')

回答 6

如果日期是datetime对象,这是一个解决方案。

import datetime
def dow(date):
    days=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
    dayNumber=date.weekday()
    print days[dayNumber]

This is a solution if the date is a datetime object.

import datetime
def dow(date):
    days=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
    dayNumber=date.weekday()
    print days[dayNumber]

回答 7

如果您将日期作为字符串,则使用pandas的时间戳记可能更容易

import pandas as pd
df = pd.Timestamp("2019-04-12")
print(df.dayofweek, df.weekday_name)

输出:

4 Friday

If you have dates as a string, it might be easier to do it using pandas’ Timestamp

import pandas as pd
df = pd.Timestamp("2019-04-12")
print(df.dayofweek, df.weekday_name)

Output:

4 Friday

回答 8

datetime库有时会因strptime()提供错误,因此我切换到dateutil库。这是一个如何使用它的示例:

from dateutil import parser
parser.parse('January 11, 2010').strftime("%a")

您从中获得的输出是'Mon'。如果要将输出显示为“星期一”,请使用以下命令:

parser.parse('January 11, 2010').strftime("%A")

这对我来说很快。使用日期时间库时遇到问题,因为我想存储工作日名称而不是工作日编号,并且使用日期时间库的格式引起了问题。如果您对此没有问题,那就太好了!如果您愿意,您绝对可以这样做,因为它也具有更简单的语法。希望这可以帮助。

datetime library sometimes gives errors with strptime() so I switched to dateutil library. Here’s an example of how you can use it :

from dateutil import parser
parser.parse('January 11, 2010').strftime("%a")

The output that you get from this is 'Mon'. If you want the output as ‘Monday’, use the following :

parser.parse('January 11, 2010').strftime("%A")

This worked for me pretty quickly. I was having problems while using the datetime library because I wanted to store the weekday name instead of weekday number and the format from using the datetime library was causing problems. If you’re not having problems with this, great! If you are, you cand efinitely go for this as it has a simpler syntax as well. Hope this helps.


回答 9

假设给定日期,月份和年份,则可以执行以下操作:

import datetime
DayL = ['Mon','Tues','Wednes','Thurs','Fri','Satur','Sun']
date = DayL[datetime.date(year,month,day).weekday()] + 'day'
#Set day, month, year to your value
#Now, date is set as an actual day, not a number from 0 to 6.

print(date)

Assuming you are given the day, month, and year, you could do:

import datetime
DayL = ['Mon','Tues','Wednes','Thurs','Fri','Satur','Sun']
date = DayL[datetime.date(year,month,day).weekday()] + 'day'
#Set day, month, year to your value
#Now, date is set as an actual day, not a number from 0 to 6.

print(date)

回答 10

假设您有timeStamp:字符串变量,YYYY-MM-DD HH:MM:SS

第1步:将其转换为带有打击代码的dateTime函数…

df['timeStamp'] = pd.to_datetime(df['timeStamp'])

第2步:现在您可以提取以下所有必需的功能,这将为每个小时,月份,星期几,年,日期创建新的列

df['Hour'] = df['timeStamp'].apply(lambda time: time.hour)
df['Month'] = df['timeStamp'].apply(lambda time: time.month)
df['Day of Week'] = df['timeStamp'].apply(lambda time: time.dayofweek)
df['Year'] = df['timeStamp'].apply(lambda t: t.year)
df['Date'] = df['timeStamp'].apply(lambda t: t.day)

Say you have timeStamp: String variable, YYYY-MM-DD HH:MM:SS

step 1: convert it to dateTime function with blow code…

df['timeStamp'] = pd.to_datetime(df['timeStamp'])

Step 2 : Now you can extract all the required feature as below which will create new Column for each of the fild- hour,month,day of week,year, date

df['Hour'] = df['timeStamp'].apply(lambda time: time.hour)
df['Month'] = df['timeStamp'].apply(lambda time: time.month)
df['Day of Week'] = df['timeStamp'].apply(lambda time: time.dayofweek)
df['Year'] = df['timeStamp'].apply(lambda t: t.year)
df['Date'] = df['timeStamp'].apply(lambda t: t.day)

回答 11

如果您有理由避免使用datetime模块,那么此功能将起作用。

注意:假定从儒略历到公历的更改发生在1582年。如果对于您感兴趣的日历不正确,则请更改年份> 1582:的行。

def dow(year,month,day):
    """ day of week, Sunday = 1, Saturday = 7
     http://en.wikipedia.org/wiki/Zeller%27s_congruence """
    m, q = month, day
    if m == 1:
        m = 13
        year -= 1
    elif m == 2:
        m = 14
        year -= 1
    K = year % 100    
    J = year // 100
    f = (q + int(13*(m + 1)/5.0) + K + int(K/4.0))
    fg = f + int(J/4.0) - 2 * J
    fj = f + 5 - J
    if year > 1582:
        h = fg % 7
    else:
        h = fj % 7
    if h == 0:
        h = 7
    return h

If you have reason to avoid the use of the datetime module, then this function will work.

Note: The change from the Julian to the Gregorian calendar is assumed to have occurred in 1582. If this is not true for your calendar of interest then change the line if year > 1582: accordingly.

def dow(year,month,day):
    """ day of week, Sunday = 1, Saturday = 7
     http://en.wikipedia.org/wiki/Zeller%27s_congruence """
    m, q = month, day
    if m == 1:
        m = 13
        year -= 1
    elif m == 2:
        m = 14
        year -= 1
    K = year % 100    
    J = year // 100
    f = (q + int(13*(m + 1)/5.0) + K + int(K/4.0))
    fg = f + int(J/4.0) - 2 * J
    fj = f + 5 - J
    if year > 1582:
        h = fg % 7
    else:
        h = fj % 7
    if h == 0:
        h = 7
    return h

回答 12

如果您不仅仅依赖于datetime模块,则calendar可能是更好的选择。例如,这将为您提供日期代码:

calendar.weekday(2017,12,22);

这将给您带来美好的一天:

days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
days[calendar.weekday(2017,12,22)]

或采用python样式,作为一个衬里:

["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][calendar.weekday(2017,12,22)]

If you’re not solely reliant on the datetime module, calendar might be a better alternative. This, for example, will provide you with the day codes:

calendar.weekday(2017,12,22);

And this will give you the day itself:

days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
days[calendar.weekday(2017,12,22)]

Or in the style of python, as a one liner:

["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][calendar.weekday(2017,12,22)]

回答 13

我们可以帮助熊猫:

import pandas as pd

如上所述,在问题中,我们有:

datetime(2017, 10, 20)

如果在jupyter笔记本中执行此行,我们将得到如下输出:

datetime.datetime(2017, 10, 20, 0, 0)

使用weekday()和weekday_name:

如果您希望工作日为整数格式,请使用:

pd.to_datetime(datetime(2017, 10, 20)).weekday()

输出将是:

4

而且,如果您希望将其作为星期天,星期一,星期五等天的名称,则可以使用:

pd.to_datetime(datetime(2017, 10, 20)).weekday_name

输出将是:

'Friday'

如果在Pandas数据框中具有日期列,则:

现在假设您有一个熊猫数据框,其日期列如下所示:pdExampleDataFrame [‘Dates’]。head(5)

0   2010-04-01
1   2010-04-02
2   2010-04-03
3   2010-04-04
4   2010-04-05
Name: Dates, dtype: datetime64[ns]

现在,如果我们想知道星期一,星期二,.. etc等工作日的名称,可以使用.weekday_name以下方法:

pdExampleDataFrame.head(5)['Dates'].dt.weekday_name

输出将是:

0    Thursday
1      Friday
2    Saturday
3      Sunday
4      Monday
Name: Dates, dtype: object

而且,如果我们想从“日期”列中获取工作日的整数,则可以使用:

pdExampleDataFrame.head(5)['Dates'].apply(lambda x: x.weekday())

输出将如下所示:

0    3
1    4
2    5
3    6
4    0
Name: Dates, dtype: int64

We can take help of Pandas:

import pandas as pd

As mentioned above in the problem We have:

datetime(2017, 10, 20)

If execute this line in the jupyter notebook we have an output like this:

datetime.datetime(2017, 10, 20, 0, 0)

Using weekday() and weekday_name:

If you want weekdays in integer number format then use:

pd.to_datetime(datetime(2017, 10, 20)).weekday()

The output will be:

4

And if you want it as name of the day like Sunday, Monday, Friday, etc you can use:

pd.to_datetime(datetime(2017, 10, 20)).weekday_name

The output will be:

'Friday'

If having a dates column in Pandas dataframe then:

Now suppose if you have a pandas dataframe having a date column like this: pdExampleDataFrame[‘Dates’].head(5)

0   2010-04-01
1   2010-04-02
2   2010-04-03
3   2010-04-04
4   2010-04-05
Name: Dates, dtype: datetime64[ns]

Now If we want to know the name of the weekday like Monday, Tuesday, ..etc we can use .weekday_name as follows:

pdExampleDataFrame.head(5)['Dates'].dt.weekday_name

the output will be:

0    Thursday
1      Friday
2    Saturday
3      Sunday
4      Monday
Name: Dates, dtype: object

And if we want the integer number of weekday from this Dates column then we can use:

pdExampleDataFrame.head(5)['Dates'].apply(lambda x: x.weekday())

The output will look like this:

0    3
1    4
2    5
3    6
4    0
Name: Dates, dtype: int64

回答 14

import datetime
import calendar

day, month, year = map(int, input().split())
my_date = datetime.date(year, month, day)
print(calendar.day_name[my_date.weekday()])

输出样本

08 05 2015
Friday
import datetime
import calendar

day, month, year = map(int, input().split())
my_date = datetime.date(year, month, day)
print(calendar.day_name[my_date.weekday()])

Output Sample

08 05 2015
Friday

回答 15

import datetime
int(datetime.datetime.today().strftime('%w'))+1

这应该给您您的真实日期-1 =星期日,2 =星期一,依此类推…

import datetime
int(datetime.datetime.today().strftime('%w'))+1

this should give you your real day number – 1 = sunday, 2 = monday, etc…


回答 16

要使星期日为1到星期六为7,这是您问题的最简单解决方案:

datetime.date.today().toordinal()%7 + 1

他们全部:

import datetime

today = datetime.date.today()
sunday = today - datetime.timedelta(today.weekday()+1)

for i in range(7):
    tmp_date = sunday + datetime.timedelta(i)
    print tmp_date.toordinal()%7 + 1, '==', tmp_date.strftime('%A')

输出:

1 == Sunday
2 == Monday
3 == Tuesday
4 == Wednesday
5 == Thursday
6 == Friday
7 == Saturday

To get Sunday as 1 through Saturday as 7, this is the simplest solution to your question:

datetime.date.today().toordinal()%7 + 1

All of them:

import datetime

today = datetime.date.today()
sunday = today - datetime.timedelta(today.weekday()+1)

for i in range(7):
    tmp_date = sunday + datetime.timedelta(i)
    print tmp_date.toordinal()%7 + 1, '==', tmp_date.strftime('%A')

Output:

1 == Sunday
2 == Monday
3 == Tuesday
4 == Wednesday
5 == Thursday
6 == Friday
7 == Saturday

回答 17

这是如何将日期列表转换为日期

import datetime,time
ls={'1/1/2007','1/2/2017'}
dt=datetime.datetime.strptime(ls[1], "%m/%d/%Y")
print(dt)
print(dt.month)
print(dt.year)

here is how to convert a listof dates to date

import datetime,time
ls={'1/1/2007','1/2/2017'}
dt=datetime.datetime.strptime(ls[1], "%m/%d/%Y")
print(dt)
print(dt.month)
print(dt.year)

回答 18

使用坎伦达模块

import calendar
a=calendar.weekday(year,month,day)
days=["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]
print(days[a])

Using Canlendar Module

import calendar
a=calendar.weekday(year,month,day)
days=["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]
print(days[a])

回答 19

这是我的python3实现。

months = {'jan' : 1, 'feb' : 4, 'mar' : 4, 'apr':0, 'may':2, 'jun':5, 'jul':6, 'aug':3, 'sep':6, 'oct':1, 'nov':4, 'dec':6}
dates = {'Sunday':1, 'Monday':2, 'Tuesday':3, 'Wednesday':4, 'Thursday':5, 'Friday':6, 'Saterday':0}
ranges = {'1800-1899':2, '1900-1999':0, '2000-2099':6, '2100-2199':4, '2200-2299':2}

def getValue(val, dic):
    if(len(val)==4):
        for k,v in dic.items():
            x,y=int(k.split('-')[0]),int(k.split('-')[1])
            val = int(val)
            if(val>=x and val<=y):
                return v
    else:
        return dic[val]

def getDate(val):
    return (list(dates.keys())[list(dates.values()).index(val)]) 



def main(myDate):
    dateArray = myDate.split('-')
    # print(dateArray)
    date,month,year = dateArray[2],dateArray[1],dateArray[0]
    # print(date,month,year)

    date = int(date)
    month_v = getValue(month, months)
    year_2 = int(year[2:])
    div = year_2//4
    year_v = getValue(year, ranges)
    sumAll = date+month_v+year_2+div+year_v
    val = (sumAll)%7
    str_date = getDate(val)

    print('{} is a {}.'.format(myDate, str_date))

if __name__ == "__main__":
    testDate = '2018-mar-4'
    main(testDate)

Here is my python3 implementation.

months = {'jan' : 1, 'feb' : 4, 'mar' : 4, 'apr':0, 'may':2, 'jun':5, 'jul':6, 'aug':3, 'sep':6, 'oct':1, 'nov':4, 'dec':6}
dates = {'Sunday':1, 'Monday':2, 'Tuesday':3, 'Wednesday':4, 'Thursday':5, 'Friday':6, 'Saterday':0}
ranges = {'1800-1899':2, '1900-1999':0, '2000-2099':6, '2100-2199':4, '2200-2299':2}

def getValue(val, dic):
    if(len(val)==4):
        for k,v in dic.items():
            x,y=int(k.split('-')[0]),int(k.split('-')[1])
            val = int(val)
            if(val>=x and val<=y):
                return v
    else:
        return dic[val]

def getDate(val):
    return (list(dates.keys())[list(dates.values()).index(val)]) 



def main(myDate):
    dateArray = myDate.split('-')
    # print(dateArray)
    date,month,year = dateArray[2],dateArray[1],dateArray[0]
    # print(date,month,year)

    date = int(date)
    month_v = getValue(month, months)
    year_2 = int(year[2:])
    div = year_2//4
    year_v = getValue(year, ranges)
    sumAll = date+month_v+year_2+div+year_v
    val = (sumAll)%7
    str_date = getDate(val)

    print('{} is a {}.'.format(myDate, str_date))

if __name__ == "__main__":
    testDate = '2018-mar-4'
    main(testDate)

回答 20

使用此代码:

import pandas as pd
from datetime import datetime
print(pd.DatetimeIndex(df['give_date']).day)

use this code:

import pandas as pd
from datetime import datetime
print(pd.DatetimeIndex(df['give_date']).day)

回答 21

将numpy导入为np

def date(df):

df['weekday'] = df['date'].dt.day_name()

conditions = [(df['weekday'] == 'Sunday'),
          (df['weekday'] == 'Monday'),
          (df['weekday'] == 'Tuesday'),
          (df['weekday'] == 'Wednesday'),
          (df['weekday'] == 'Thursday'),
          (df['weekday'] == 'Friday'),
          (df['weekday'] == 'Saturday')]

choices = [0, 1, 2, 3, 4, 5, 6]

df['week'] = np.select(conditions, choices)

return df

import numpy as np

def date(df):

df['weekday'] = df['date'].dt.day_name()

conditions = [(df['weekday'] == 'Sunday'),
          (df['weekday'] == 'Monday'),
          (df['weekday'] == 'Tuesday'),
          (df['weekday'] == 'Wednesday'),
          (df['weekday'] == 'Thursday'),
          (df['weekday'] == 'Friday'),
          (df['weekday'] == 'Saturday')]

choices = [0, 1, 2, 3, 4, 5, 6]

df['week'] = np.select(conditions, choices)

return df

获取当前时间(以毫秒为单位)在Python中?

问题:获取当前时间(以毫秒为单位)在Python中?

如何在Python中获取以毫秒为单位的当前时间?

How can I get the current time in milliseconds in Python?


回答 0

根据我上面的@samplebias的评论,这是我需要做的:

import time
millis = int(round(time.time() * 1000))
print millis

快点 谢谢大家,为您的大脑屁感到抱歉。

要重用:

import time

current_milli_time = lambda: int(round(time.time() * 1000))

然后:

>>> current_milli_time()
1378761833768

For what I needed, here’s what I did, based on @samplebias’ comment above:

import time
millis = int(round(time.time() * 1000))
print millis

Quick’n’easy. Thanks all, sorry for the brain fart.

For reuse:

import time

current_milli_time = lambda: int(round(time.time() * 1000))

Then:

>>> current_milli_time()
1378761833768

回答 1

time.time()可能只提供秒的分辨率,毫秒的首选方法是datetime

from datetime import datetime
dt = datetime.now()
dt.microsecond

time.time() may only give resolution to the second, the preferred approach for milliseconds is datetime.

from datetime import datetime
dt = datetime.now()
dt.microsecond

回答 2

def TimestampMillisec64():
    return int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000) 
def TimestampMillisec64():
    return int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000) 

回答 3

3.7版开始,您可以time.time_ns()用来获取从纪元开始经过的纳秒级的时间。所以你可以做

ms = time.time_ns() // 1000000 

以毫秒为单位获取时间作为整数。

From version 3.7 you can use time.time_ns() to get time as passed nano seconds from epoch. So you can do

ms = time.time_ns() // 1000000 

to get time in mili-seconds as integer.


回答 4

只是示例代码:

import time
timestamp = int(time.time()*1000.0)

输出:1534343781311

Just sample code:

import time
timestamp = int(time.time()*1000.0)

Output: 1534343781311


回答 5

另一个解决方案是可以嵌入到自己的utils.py中的函数

import time as time_ #make sure we don't override time
def millis():
    return int(round(time_.time() * 1000))

another solution is the function you can embed into your own utils.py

import time as time_ #make sure we don't override time
def millis():
    return int(round(time_.time() * 1000))

回答 6

如果您想在代码中使用一个简单的方法来返回带有datetime的毫秒数:

from datetime import datetime
from datetime import timedelta

start_time = datetime.now()

# returns the elapsed milliseconds since the start of the program
def millis():
   dt = datetime.now() - start_time
   ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
   return ms

If you want a simple method in your code that returns the milliseconds with datetime:

from datetime import datetime
from datetime import timedelta

start_time = datetime.now()

# returns the elapsed milliseconds since the start of the program
def millis():
   dt = datetime.now() - start_time
   ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
   return ms

回答 7

我发现以毫秒为单位获取当前UTC时间的最简单方法是:

# timeutil.py
import datetime


def get_epochtime_ms():
    return round(datetime.datetime.utcnow().timestamp() * 1000)

# sample.py
import timeutil


timeutil.get_epochtime_ms()

The simpliest way I’ve found to get the current UTC time in milliseconds is:

# timeutil.py
import datetime


def get_epochtime_ms():
    return round(datetime.datetime.utcnow().timestamp() * 1000)

# sample.py
import timeutil


timeutil.get_epochtime_ms()

回答 8

如果您担心测量经过的时间,则应使用单调时钟(python 3)。该时钟不受系统时钟更新的影响,例如,您会看到NTP查询是否调整了系统时间。

>>> import time
>>> millis = round(time.monotonic() * 1000)

它提供了以秒为单位的参考时间,可用于以后进行比较以测量经过的时间。

If you’re concerned about measuring elapsed time, you should use the monotonic clock (python 3). This clock is not affected by system clock updates like you would see if an NTP query adjusted your system time, for example.

>>> import time
>>> millis = round(time.monotonic() * 1000)

It provides a reference time in seconds that can be used to compare later to measure elapsed time.


回答 9

如果您使用我的代码(如下所示),则时间将以秒为单位,然后在十进制后为毫秒。我认为Windows和Unix之间有区别-如果有区别,请发表评论。

from time import time

x = time()
print(x)

我的结果(在Windows上)是:

1576095264.2682993

编辑:没有区别:)谢谢tc0nn

If you use my code (below), the time will appear in seconds, then, after a decimal, milliseconds. I think that there is a difference between Windows and Unix – please comment if there is.

from time import time

x = time()
print(x)

my result (on Windows) was:

1576095264.2682993

EDIT: There is no difference:) Thanks tc0nn


回答 10

这些乘以1000毫秒的乘法对于解决或使某些先决条件可接受可能是不错的选择。它可以用来填补数据库中实际上从未使用过的空白。虽然,对于需要精确定时的实际情况,它最终会失败。我不建议任何人将这种方法用于需要执行操作或在特定时间进行处理的关键任务操作。

例如:在美国,双向ping是30-80毫秒…您不能将其四舍五入并有效地使用它。

我自己的示例要求每秒执行一次任务,这意味着如果我在响应第一个任务后将其四舍五入,仍然会导致处理时间乘以每个主循环周期。最终每60秒调用一次函数。每天大约是1440 ..不太准确。

对于那些希望寻求更准确推理而不是解决从未真正使用过数据库缺口的人们来说,这只是一个想法。

These multiplications to 1000 for milliseconds may be decent for solving or making some prerequisite acceptable. It could be used to fill a gap in your database which doesn’t really ever use it. Although, for real situations which require precise timing it would ultimately fail. I wouldn’t suggest anyone use this method for mission-critical operations which require actions, or processing at specific timings.

For example: round-trip pings being 30-80ms in the USA… You couldn’t just round that up and use it efficiently.

My own example requires tasks at every second which means if I rounded up after the first tasks responded I would still incur the processing time multiplied every main loop cycle. This ended up being a total function call every 60 seconds. that’s ~1440 a day.. not too accurate.

Just a thought for people looking for more accurate reasoning beyond solving a database gap which never really uses it.


回答 11

这是使用datetime适用于Python 3 的模块的另一种解决方案。

datetime.datetime.timestamp(datetime.datetime.now())

Just another solution using the datetime module for Python 3.

datetime.datetime.timestamp(datetime.datetime.now())

如何在python中识别未知的日期时间时区

问题:如何在python中识别未知的日期时间时区

我需要做什么

我有一个不带时区的datetime对象,我需要向其添加一个时区,以便能够将其与其他时区可感知的datetime对象进行比较。对于这一旧情况,我不想将我的整个应用程序转换为时区。

我尝试过的

首先,演示该问题:

Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import pytz
>>> unaware = datetime.datetime(2011,8,15,8,15,12,0)
>>> unaware
datetime.datetime(2011, 8, 15, 8, 15, 12)
>>> aware = datetime.datetime(2011,8,15,8,15,12,0,pytz.UTC)
>>> aware
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> aware == unaware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes

首先,我尝试了astimezone:

>>> unaware.astimezone(pytz.UTC)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime
>>>

这次失败并不令人惊讶,因为它实际上是在尝试进行转换。替换似乎是一个更好的选择(根据Python:如何获取“时区感知”的datetime.today()值?):

>>> unaware.replace(tzinfo=pytz.UTC)
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> unaware == aware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
>>> 

但是正如您所看到的,replace似乎设置了tzinfo,但没有使对象知道。我准备回过头来解析输入字符串以在解析它之前有一个时区(如果重要的话,我正在使用dateutil进行解析),但这似乎令人难以置信。

另外,我在python 2.6和python 2.7中都尝试过,结果相同。

语境

我正在为某些数据文件编写解析器。我需要支持一种旧格式,其中日期字符串没有时区指示符。我已经修复了数据源,但是我仍然需要支持旧数据格式。由于各种业务BS的原因,不能一次转换旧数据。通常,我不喜欢对默认时区进行硬编码的想法,在这种情况下,这似乎是最好的选择。我完全有把握地知道所有有问题的旧数据都位于UTC中,因此在这种情况下,我准备接受默认设置的风险。

What I need to do

I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezone-aware datetime objects. I do not want to convert my entire application to timezone unaware for this one legacy case.

What I’ve Tried

First, to demonstrate the problem:

Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import pytz
>>> unaware = datetime.datetime(2011,8,15,8,15,12,0)
>>> unaware
datetime.datetime(2011, 8, 15, 8, 15, 12)
>>> aware = datetime.datetime(2011,8,15,8,15,12,0,pytz.UTC)
>>> aware
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> aware == unaware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes

First, I tried astimezone:

>>> unaware.astimezone(pytz.UTC)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime
>>>

It’s not terribly surprising this failed, since it’s actually trying to do a conversion. Replace seemed like a better choice (as per Python: How to get a value of datetime.today() that is “timezone aware”?):

>>> unaware.replace(tzinfo=pytz.UTC)
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> unaware == aware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
>>> 

But as you can see, replace seems to set the tzinfo, but not make the object aware. I’m getting ready to fall back to doctoring the input string to have a timezone before parsing it (I’m using dateutil for parsing, if that matters), but that seems incredibly kludgy.

Also, I’ve tried this in both python 2.6 and python 2.7, with the same results.

Context

I am writing a parser for some data files. There is an old format I need to support where the date string does not have a timezone indicator. I’ve already fixed the data source, but I still need to support the legacy data format. A one time conversion of the legacy data is not an option for various business BS reasons. While in general, I do not like the idea of hard-coding a default timezone, in this case it seems like the best option. I know with reasonable confidence that all the legacy data in question is in UTC, so I’m prepared to accept the risk of defaulting to that in this case.


回答 0

通常,要使原始的datetime时区感知,请使用localize方法

import datetime
import pytz

unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC)

now_aware = pytz.utc.localize(unaware)
assert aware == now_aware

对于UTC时区,localize由于没有夏令时计算可处理,因此实际上没有必要使用:

now_aware = unaware.replace(tzinfo=pytz.UTC)

作品。(.replace返回一个新的日期时间;它不会修改unaware。)

In general, to make a naive datetime timezone-aware, use the localize method:

import datetime
import pytz

unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC)

now_aware = pytz.utc.localize(unaware)
assert aware == now_aware

For the UTC timezone, it is not really necessary to use localize since there is no daylight savings time calculation to handle:

now_aware = unaware.replace(tzinfo=pytz.UTC)

works. (.replace returns a new datetime; it does not modify unaware.)


回答 1

所有这些示例都使用一个外部模块,但是您可以仅使用datetime模块来达到相同的结果,SO答案中也有介绍:

from datetime import datetime
from datetime import timezone

dt = datetime.now()
dt.replace(tzinfo=timezone.utc)

print(dt.replace(tzinfo=timezone.utc).isoformat())
'2017-01-12T22:11:31+00:00'

更少的依赖项,没有pytz问题。

注意:如果您希望将其与python3和python2一起使用,则也可以将其用于时区导入(针对UTC进行硬编码):

try:
    from datetime import timezone
    utc = timezone.utc
except ImportError:
    #Hi there python2 user
    class UTC(tzinfo):
        def utcoffset(self, dt):
            return timedelta(0)
        def tzname(self, dt):
            return "UTC"
        def dst(self, dt):
            return timedelta(0)
    utc = UTC()

All of these examples use an external module, but you can achieve the same result using just the datetime module, as also presented in this SO answer:

from datetime import datetime
from datetime import timezone

dt = datetime.now()
dt.replace(tzinfo=timezone.utc)

print(dt.replace(tzinfo=timezone.utc).isoformat())
'2017-01-12T22:11:31+00:00'

Fewer dependencies and no pytz issues.

NOTE: If you wish to use this with python3 and python2, you can use this as well for the timezone import (hardcoded for UTC):

try:
    from datetime import timezone
    utc = timezone.utc
except ImportError:
    #Hi there python2 user
    class UTC(tzinfo):
        def utcoffset(self, dt):
            return timedelta(0)
        def tzname(self, dt):
            return "UTC"
        def dst(self, dt):
            return timedelta(0)
    utc = UTC()

回答 2

我曾经使用过从dt_aware到dt_unaware

dt_unaware = dt_aware.replace(tzinfo=None)

和dt_unware到dt_aware

from pytz import timezone
localtz = timezone('Europe/Lisbon')
dt_aware = localtz.localize(dt_unware)

但之前回答也是一个很好的解决方案。

I had use from dt_aware to dt_unaware

dt_unaware = dt_aware.replace(tzinfo=None)

and dt_unware to dt_aware

from pytz import timezone
localtz = timezone('Europe/Lisbon')
dt_aware = localtz.localize(dt_unware)

but answer before is also a good solution.


回答 3

我在Django中使用以下语句将无意识的时间转换为有意识的时间:

from django.utils import timezone

dt_aware = timezone.make_aware(dt_unaware, timezone.get_current_timezone())

I use this statement in Django to convert an unaware time to an aware:

from django.utils import timezone

dt_aware = timezone.make_aware(dt_unaware, timezone.get_current_timezone())

回答 4

我同意之前的回答,如果可以开始使用UTC,也可以。但我认为这也是人们使用tz感知值(其日期时间具有非UTC本地时区)的常见情况

如果只是按名称命名,则可能会推断replace()将适用,并产生正确的日期时间感知对象。不是这种情况。

replace(tzinfo = …)的行为似乎是随机的。因此,它是没有用的。不要使用这个!

本地化是正确使用的功能。例:

localdatetime_aware = tz.localize(datetime_nonaware)

或更完整的示例:

import pytz
from datetime import datetime
pytz.timezone('Australia/Melbourne').localize(datetime.now())

给我一个当前本地时间的时区感知日期时间值:

datetime.datetime(2017, 11, 3, 7, 44, 51, 908574, tzinfo=<DstTzInfo 'Australia/Melbourne' AEDT+11:00:00 DST>)

I agree with the previous answers, and is fine if you are ok to start in UTC. But I think it is also a common scenario for people to work with a tz aware value that has a datetime that has a non UTC local timezone.

If you were to just go by name, one would probably infer replace() will be applicable and produce the right datetime aware object. This is not the case.

the replace( tzinfo=… ) seems to be random in its behaviour. It is therefore useless. Do not use this!

localize is the correct function to use. Example:

localdatetime_aware = tz.localize(datetime_nonaware)

Or a more complete example:

import pytz
from datetime import datetime
pytz.timezone('Australia/Melbourne').localize(datetime.now())

gives me a timezone aware datetime value of the current local time:

datetime.datetime(2017, 11, 3, 7, 44, 51, 908574, tzinfo=<DstTzInfo 'Australia/Melbourne' AEDT+11:00:00 DST>)

回答 5

使用dateutil.tz.tzlocal()来获取时区在你的使用datetime.datetime.now()datetime.datetime.astimezone()

from datetime import datetime
from dateutil import tz

unlocalisedDatetime = datetime.now()

localisedDatetime1 = datetime.now(tz = tz.tzlocal())
localisedDatetime2 = datetime(2017, 6, 24, 12, 24, 36, tz.tzlocal())
localisedDatetime3 = unlocalisedDatetime.astimezone(tz = tz.tzlocal())
localisedDatetime4 = unlocalisedDatetime.replace(tzinfo = tz.tzlocal())

请注意,这datetime.astimezone将首先将您的datetime对象转换为UTC,然后转换为时区,这datetime.replace与使用原始时区信息为进行调用相同None

Use dateutil.tz.tzlocal() to get the timezone in your usage of datetime.datetime.now() and datetime.datetime.astimezone():

from datetime import datetime
from dateutil import tz

unlocalisedDatetime = datetime.now()

localisedDatetime1 = datetime.now(tz = tz.tzlocal())
localisedDatetime2 = datetime(2017, 6, 24, 12, 24, 36, tz.tzlocal())
localisedDatetime3 = unlocalisedDatetime.astimezone(tz = tz.tzlocal())
localisedDatetime4 = unlocalisedDatetime.replace(tzinfo = tz.tzlocal())

Note that datetime.astimezone will first convert your datetime object to UTC then into the timezone, which is the same as calling datetime.replace with the original timezone information being None.


回答 6

这将@Sérgio和@unutbu的答案整理成代码。它将与pytz.timezone对象或IANA时区字符串“兼容” 。

def make_tz_aware(dt, tz='UTC', is_dst=None):
    """Add timezone information to a datetime object, only if it is naive."""
    tz = dt.tzinfo or tz
    try:
        tz = pytz.timezone(tz)
    except AttributeError:
        pass
    return tz.localize(dt, is_dst=is_dst) 

似乎应该做什么datetime.localize()(或.inform().awarify()),接受tz参数的字符串和时区对象,如果未指定时区,则默认为UTC。

This codifies @Sérgio and @unutbu’s answers. It will “just work” with either a pytz.timezone object or an IANA Time Zone string.

def make_tz_aware(dt, tz='UTC', is_dst=None):
    """Add timezone information to a datetime object, only if it is naive."""
    tz = dt.tzinfo or tz
    try:
        tz = pytz.timezone(tz)
    except AttributeError:
        pass
    return tz.localize(dt, is_dst=is_dst) 

This seems like what datetime.localize() (or .inform() or .awarify()) should do, accept both strings and timezone objects for the tz argument and default to UTC if no time zone is specified.


回答 7

Python 3.9添加了zoneinfo模块,因此现在仅需要标准库!

from zoneinfo import ZoneInfo
from datetime import datetime
unaware = datetime(2020, 10, 31, 12)

附加时区:

>>> unaware.replace(tzinfo=ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 12:00:00+09:00'

附加系统的本地时区:

>>> unaware.replace(tzinfo=ZoneInfo('localtime'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> str(_)
'2020-10-31 12:00:00+01:00'

随后,它将正确转换为其他时区:

>>> unaware.replace(tzinfo=ZoneInfo('localtime')).astimezone(ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 20:00:00+09:00'

可用时区的维基百科列表


有一个backport允许在Python 3.6至3.8中使用

sudo pip install backports.zoneinfo

然后:

from backports.zoneinfo import ZoneInfo

Python 3.9 adds the zoneinfo module so now only the the standard library is needed!

from zoneinfo import ZoneInfo
from datetime import datetime
unaware = datetime(2020, 10, 31, 12)

Attach a timezone:

>>> unaware.replace(tzinfo=ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 12:00:00+09:00'

Attach the system’s local timezone:

>>> unaware.replace(tzinfo=ZoneInfo('localtime'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> str(_)
'2020-10-31 12:00:00+01:00'

Subsequently it is properly converted to other timezones:

>>> unaware.replace(tzinfo=ZoneInfo('localtime')).astimezone(ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 20:00:00+09:00'

Wikipedia list of available time zones


There is a backport to allow use in Python 3.6 to 3.8:

sudo pip install backports.zoneinfo

Then:

from backports.zoneinfo import ZoneInfo

回答 8

以unutbu的答案格式;我制作了一个实用程序模块,以更直观的语法处理此类问题。可以通过pip安装。

import datetime
import saturn

unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
now_aware = saturn.fix_naive(unaware)

now_aware_madrid = saturn.fix_naive(unaware, 'Europe/Madrid')

In the format of unutbu’s answer; I made a utility module that handles things like this, with more intuitive syntax. Can be installed with pip.

import datetime
import saturn

unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
now_aware = saturn.fix_naive(unaware)

now_aware_madrid = saturn.fix_naive(unaware, 'Europe/Madrid')

回答 9

对于那些只想使时区知道日期时间的人

import datetime
import pytz

datetime.datetime(2019, 12, 7, tzinfo=pytz.UTC)

for those that just want to make a timezone aware datetime

import datetime
import pytz

datetime.datetime(2019, 12, 7, tzinfo=pytz.UTC)

回答 10

对Python来说还很陌生,我遇到了同样的问题。我发现此解决方案非常简单,对我来说也可以正常工作(Python 3.6):

unaware=parser.parse("2020-05-01 0:00:00")
aware=unaware.replace(tzinfo=tz.tzlocal()).astimezone(tz.tzlocal())

quite new to Python and I encountered the same issue. I find this solution quite simple and for me it works fine (Python 3.6):

unaware=parser.parse("2020-05-01 0:00:00")
aware=unaware.replace(tzinfo=tz.tzlocal()).astimezone(tz.tzlocal())

回答 11

在时区之间切换

import pytz
from datetime import datetime

other_tz = pytz.timezone('Europe/Madrid')

# From random aware datetime...
aware_datetime = datetime.utcnow().astimezone(other_tz)
>> 2020-05-21 08:28:26.984948+02:00

# 1. Change aware datetime to UTC and remove tzinfo to obtain an unaware datetime
unaware_datetime = aware_datetime.astimezone(pytz.UTC).replace(tzinfo=None)
>> 2020-05-21 06:28:26.984948

# 2. Set tzinfo to UTC directly on an unaware datetime to obtain an utc aware datetime
aware_datetime_utc = unaware_datetime.replace(tzinfo=pytz.UTC)
>> 2020-05-21 06:28:26.984948+00:00

# 3. Convert the aware utc datetime into another timezone
reconverted_aware_datetime = aware_datetime_utc.astimezone(other_tz)
>> 2020-05-21 08:28:26.984948+02:00

# Initial Aware Datetime and Reconverted Aware Datetime are equal
print(aware_datetime1 == aware_datetime2)
>> True

Changing between timezones

import pytz
from datetime import datetime

other_tz = pytz.timezone('Europe/Madrid')

# From random aware datetime...
aware_datetime = datetime.utcnow().astimezone(other_tz)
>> 2020-05-21 08:28:26.984948+02:00

# 1. Change aware datetime to UTC and remove tzinfo to obtain an unaware datetime
unaware_datetime = aware_datetime.astimezone(pytz.UTC).replace(tzinfo=None)
>> 2020-05-21 06:28:26.984948

# 2. Set tzinfo to UTC directly on an unaware datetime to obtain an utc aware datetime
aware_datetime_utc = unaware_datetime.replace(tzinfo=pytz.UTC)
>> 2020-05-21 06:28:26.984948+00:00

# 3. Convert the aware utc datetime into another timezone
reconverted_aware_datetime = aware_datetime_utc.astimezone(other_tz)
>> 2020-05-21 08:28:26.984948+02:00

# Initial Aware Datetime and Reconverted Aware Datetime are equal
print(aware_datetime1 == aware_datetime2)
>> True

Python日期时间到没有微秒组件的字符串

问题:Python日期时间到没有微秒组件的字符串

我正在将UTC时间字符串添加到当前仅包含Amsterdam(!)时间字符串的Bitbucket API响应中。为了与其他地方返回的UTC时间字符串保持一致,请使用所需的格式2011-11-03 11:07:04(后跟+00:00,但这不是紧密联系)。

什么是创建这样一个字符串(最好的方式,而不从一微秒组件)datetime的实例微秒组成部分?

>>> import datetime
>>> print unicode(datetime.datetime.now())
2011-11-03 11:13:39.278026

我会添加出现在我身上的最佳选择作为可能的答案,但是可能会有更优雅的解决方案。

编辑:我应该提一下,我实际上并不是打印当前时间-我曾经datetime.now提供一个简单的例子。因此,该解决方案不应假定datetime其接收到的任何实例都将包含微秒组件。

I’m adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is 2011-11-03 11:07:04 (followed by +00:00, but that’s not germane).

What’s the best way to create such a string (without a microsecond component) from a datetime instance with a microsecond component?

>>> import datetime
>>> print unicode(datetime.datetime.now())
2011-11-03 11:13:39.278026

I’ll add the best option that’s occurred to me as a possible answer, but there may well be a more elegant solution.

Edit: I should mention that I’m not actually printing the current time – I used datetime.now to provide a quick example. So the solution should not assume that any datetime instances it receives will include microsecond components.


回答 0

如果要以datetime不同于标准格式的特定格式格式化对象,则最好明确指定该格式:

>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'

有关指令的说明,请参见的文档datetime.strftime()%

If you want to format a datetime object in a specific format that is different from the standard format, it’s best to explicitly specify that format:

>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'

See the documentation of datetime.strftime() for an explanation of the % directives.


回答 1

>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07
>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07

回答 2

在Python 3.6中:

from datetime import datetime
datetime.datetime.now().isoformat(' ', 'seconds')
'2017-01-11 14:41:33'

https://docs.python.org/3.6/library/datetime.html#datetime.datetime.isoformat

In Python 3.6:

from datetime import datetime
datetime.datetime.now().isoformat(' ', 'seconds')
'2017-01-11 14:41:33'

https://docs.python.org/3.6/library/datetime.html#datetime.datetime.isoformat


回答 3

这就是我做到的方式。ISO格式:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
# Returns: '2017-01-23T14:58:07'

如果您不想使用ISO格式,则可以替换为’T’:

datetime.datetime.now().replace(microsecond=0).isoformat(' ')
# Returns: '2017-01-23 15:05:27'

This is the way I do it. ISO format:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
# Returns: '2017-01-23T14:58:07'

You can replace the ‘T’ if you don’t want ISO format:

datetime.datetime.now().replace(microsecond=0).isoformat(' ')
# Returns: '2017-01-23 15:05:27'

回答 4

另一个选择:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 11:31:28'

默认情况下,这使用本地时间,如果您需要UTC,则可以使用以下时间:

>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
'2011-11-03 18:32:20'

Yet another option:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 11:31:28'

By default this uses local time, if you need UTC you can use the following:

>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
'2011-11-03 18:32:20'

回答 5

通过切片保留所需的前19个字符:

>>> str(datetime.datetime.now())[:19]
'2011-11-03 14:37:50'

Keep the first 19 characters that you wanted via slicing:

>>> str(datetime.datetime.now())[:19]
'2011-11-03 14:37:50'

回答 6

我通常这样做:

import datetime
now = datetime.datetime.now()
now = now.replace(microsecond=0)  # To print now without microsecond.

# To print now:
print(now)

输出:

2019-01-13 14:40:28

I usually do:

import datetime
now = datetime.datetime.now()
now = now.replace(microsecond=0)  # To print now without microsecond.

# To print now:
print(now)

output:

2019-01-13 14:40:28

回答 7

由于并非所有datetime.datetime实例都具有微秒成分(即当它为零时),因此可以将字符串划分为“”。并只取第一项,它将始终有效:

unicode(datetime.datetime.now()).partition('.')[0]

Since not all datetime.datetime instances have a microsecond component (i.e. when it is zero), you can partition the string on a “.” and take only the first item, which will always work:

unicode(datetime.datetime.now()).partition('.')[0]

回答 8

我们可以尝试如下

import datetime

date_generated = datetime.datetime.now()
date_generated.replace(microsecond=0).isoformat(' ').partition('+')[0]

We can try something like below

import datetime

date_generated = datetime.datetime.now()
date_generated.replace(microsecond=0).isoformat(' ').partition('+')[0]

回答 9

我发现这是最简单的方法。

>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>> 

I found this to be the simplest way.

>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>> 

回答 10

我之所以使用它,是因为我可以更好地理解并记住它(日期时间格式也可以根据您的选择进行自定义):-

import datetime
moment = datetime.datetime.now()
print("{}/{}/{} {}:{}:{}".format(moment.day, moment.month, moment.year,
                                 moment.hour, moment.minute, moment.second))

This I use because I can understand and hence remember it better (and date time format also can be customized based on your choice) :-

import datetime
moment = datetime.datetime.now()
print("{}/{}/{} {}:{}:{}".format(moment.day, moment.month, moment.year,
                                 moment.hour, moment.minute, moment.second))

如何使用datetime Python模块计算从当前日期起六个月的日期?

问题:如何使用datetime Python模块计算从当前日期起六个月的日期?

我正在使用datetime Python模块。我想计算从当前日期起6个月的日期。有人可以给我一点帮助吗?

我要从当前日期起6个月生成日期的原因是要产生一个审阅日期。如果用户将数据输入到系统中,则其输入日期为6个月。

I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?

The reason I want to generate a date 6 months from the current date is to produce a review date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data.


回答 0

我发现此解决方案很好。(这使用python-dateutil扩展名

from datetime import date
from dateutil.relativedelta import relativedelta

six_months = date.today() + relativedelta(months=+6)

这种方法的优点是可以处理28、30、31天等问题。这在处理业务规则和业务情景(例如生成发票等)时非常有用。

$ date(2010,12,31)+relativedelta(months=+1)
  datetime.date(2011, 1, 31)

$ date(2010,12,31)+relativedelta(months=+2)
  datetime.date(2011, 2, 28)

I found this solution to be good. (This uses the python-dateutil extension)

from datetime import date
from dateutil.relativedelta import relativedelta

six_months = date.today() + relativedelta(months=+6)

The advantage of this approach is that it takes care of issues with 28, 30, 31 days etc. This becomes very useful in handling business rules and scenarios (say invoice generation etc.)

$ date(2010,12,31)+relativedelta(months=+1)
  datetime.date(2011, 1, 31)

$ date(2010,12,31)+relativedelta(months=+2)
  datetime.date(2011, 2, 28)

回答 1

好吧,这取决于您从当前日期算起的6个月的意思。

  1. 使用自然月份:

    (day, month, year) = (day, (month + 5) % 12 + 1, year + (month + 5)/12)
  2. 使用银行家的定义6 * 30:

    date += datetime.timedelta(6 * 30)

Well, that depends what you mean by 6 months from the current date.

  1. Using natural months:

    (day, month, year) = (day, (month + 5) % 12 + 1, year + (month + 5)/12)
    
  2. Using a banker’s definition, 6*30:

    date += datetime.timedelta(6 * 30)
    

回答 2

使用Python 3.x,您可以这样做:

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

date = datetime.now()
print(date)
# 2018-09-24 13:24:04.007620

date = date + relativedelta(months=+6)
print(date)
# 2019-03-24 13:24:04.007620

但您将需要安装python-dateutil模块:

pip install python-dateutil

With Python 3.x you can do it like this:

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

date = datetime.now()
print(date)
# 2018-09-24 13:24:04.007620

date = date + relativedelta(months=+6)
print(date)
# 2019-03-24 13:24:04.007620

but you will need to install python-dateutil module:

pip install python-dateutil

回答 3

对于月初的计算:

from datetime import timedelta
from dateutil.relativedelta import relativedelta

end_date = start_date + relativedelta(months=delta_period) + timedelta(days=-delta_period)

For beginning of month to month calculation:

from datetime import timedelta
from dateutil.relativedelta import relativedelta

end_date = start_date + relativedelta(months=delta_period) + timedelta(days=-delta_period)

回答 4

“ 6个月”是什么意思?

是2009-02-13 + 6个月== 2009-08-13吗?还是2009-02-13 + 6 * 30天?

import mx.DateTime as dt

#6 Months
dt.now()+dt.RelativeDateTime(months=6)
#result is '2009-08-13 16:28:00.84'

#6*30 days
dt.now()+dt.RelativeDateTime(days=30*6)
#result is '2009-08-12 16:30:03.35'

有关mx.DateTime的更多信息

What do you mean by “6 months”?

Is 2009-02-13 + 6 months == 2009-08-13? Or is it 2009-02-13 + 6*30 days?

import mx.DateTime as dt

#6 Months
dt.now()+dt.RelativeDateTime(months=6)
#result is '2009-08-13 16:28:00.84'

#6*30 days
dt.now()+dt.RelativeDateTime(days=30*6)
#result is '2009-08-12 16:30:03.35'

More info about mx.DateTime


回答 5

因此,这是一个示例dateutil.relativedelta,我发现该示例可用于遍历过去的一年,每次都跳过一个月到当前日期:

>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> today = datetime.datetime.today()
>>> month_count = 0
>>> while month_count < 12:
...  day = today - relativedelta(months=month_count)
...  print day
...  month_count += 1
... 
2010-07-07 10:51:45.187968
2010-06-07 10:51:45.187968
2010-05-07 10:51:45.187968
2010-04-07 10:51:45.187968
2010-03-07 10:51:45.187968
2010-02-07 10:51:45.187968
2010-01-07 10:51:45.187968
2009-12-07 10:51:45.187968
2009-11-07 10:51:45.187968
2009-10-07 10:51:45.187968
2009-09-07 10:51:45.187968
2009-08-07 10:51:45.187968

与其他答案一样,您必须弄清楚“从现在起6个月后”的实际含义。如果您的意思是“未来六年的每月的当日”,则可以这样做:

datetime.datetime.now() + relativedelta(months=6)

So, here is an example of the dateutil.relativedelta which I found useful for iterating through the past year, skipping a month each time to the present date:

>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> today = datetime.datetime.today()
>>> month_count = 0
>>> while month_count < 12:
...  day = today - relativedelta(months=month_count)
...  print day
...  month_count += 1
... 
2010-07-07 10:51:45.187968
2010-06-07 10:51:45.187968
2010-05-07 10:51:45.187968
2010-04-07 10:51:45.187968
2010-03-07 10:51:45.187968
2010-02-07 10:51:45.187968
2010-01-07 10:51:45.187968
2009-12-07 10:51:45.187968
2009-11-07 10:51:45.187968
2009-10-07 10:51:45.187968
2009-09-07 10:51:45.187968
2009-08-07 10:51:45.187968

As with the other answers, you have to figure out what you actually mean by “6 months from now.” If you mean “today’s day of the month in the month six years in the future” then this would do:

datetime.datetime.now() + relativedelta(months=6)

回答 6

此解决方案在12月正确运行,而此页面上的大多数答案都无效。在使用模数(%)或整数除法(//)之前,您需要首先将月份从基数1(即Jan = 1)转换为基数0(即Jan = 0),否则11月(11)加1个月为您提供12 ,当找到余数(12%12)时得到0。

(也不要建议“((月%12)+ 1”或10月+1 = 12月!)

def AddMonths(d,x):
    newmonth = ((( d.month - 1) + x ) % 12 ) + 1
    newyear  = int(d.year + ((( d.month - 1) + x ) / 12 ))
    return datetime.date( newyear, newmonth, d.day)

但是…这不能解决1月31日+一个月之类的问题。因此,我们回到OP-您增加一个月意味着什么?一种解决方案是回溯到有效的一天,因为大多数人会假设jan的最后一天加上一个月等于2月的最后一天。这也适用于负数个月。证明:

>>> import datetime
>>> AddMonths(datetime.datetime(2010,8,25),1)
datetime.date(2010, 9, 25)
>>> AddMonths(datetime.datetime(2010,8,25),4)
datetime.date(2010, 12, 25)
>>> AddMonths(datetime.datetime(2010,8,25),5)
datetime.date(2011, 1, 25)
>>> AddMonths(datetime.datetime(2010,8,25),13)
datetime.date(2011, 9, 25)
>>> AddMonths(datetime.datetime(2010,8,25),24)
datetime.date(2012, 8, 25)
>>> AddMonths(datetime.datetime(2010,8,25),-1)
datetime.date(2010, 7, 25)
>>> AddMonths(datetime.datetime(2010,8,25),0)
datetime.date(2010, 8, 25)
>>> AddMonths(datetime.datetime(2010,8,25),-12)
datetime.date(2009, 8, 25)
>>> AddMonths(datetime.datetime(2010,8,25),-8)
datetime.date(2009, 12, 25)
>>> AddMonths(datetime.datetime(2010,8,25),-7)
datetime.date(2010, 1, 25)>>> 

This solution works correctly for December, which most of the answers on this page do not. You need to first shift the months from base 1 (ie Jan = 1) to base 0 (ie Jan = 0) before using modulus ( % ) or integer division ( // ), otherwise November (11) plus 1 month gives you 12, which when finding the remainder ( 12 % 12 ) gives 0.

(And dont suggest “(month % 12) + 1” or Oct + 1 = december!)

def AddMonths(d,x):
    newmonth = ((( d.month - 1) + x ) % 12 ) + 1
    newyear  = int(d.year + ((( d.month - 1) + x ) / 12 ))
    return datetime.date( newyear, newmonth, d.day)

However … This doesnt account for problem like Jan 31 + one month. So we go back to the OP – what do you mean by adding a month? One solution is to backtrack until you get to a valid day, given that most people would presume the last day of jan, plus one month, equals the last day of Feb. This will work on negative numbers of months too. Proof:

>>> import datetime
>>> AddMonths(datetime.datetime(2010,8,25),1)
datetime.date(2010, 9, 25)
>>> AddMonths(datetime.datetime(2010,8,25),4)
datetime.date(2010, 12, 25)
>>> AddMonths(datetime.datetime(2010,8,25),5)
datetime.date(2011, 1, 25)
>>> AddMonths(datetime.datetime(2010,8,25),13)
datetime.date(2011, 9, 25)
>>> AddMonths(datetime.datetime(2010,8,25),24)
datetime.date(2012, 8, 25)
>>> AddMonths(datetime.datetime(2010,8,25),-1)
datetime.date(2010, 7, 25)
>>> AddMonths(datetime.datetime(2010,8,25),0)
datetime.date(2010, 8, 25)
>>> AddMonths(datetime.datetime(2010,8,25),-12)
datetime.date(2009, 8, 25)
>>> AddMonths(datetime.datetime(2010,8,25),-8)
datetime.date(2009, 12, 25)
>>> AddMonths(datetime.datetime(2010,8,25),-7)
datetime.date(2010, 1, 25)>>> 

回答 7

我知道这是6个月,但是如果您要添加一个月,答案就会在Google中显示为“在python中添加月份”:

import calendar

date = datetime.date.today()    //Or your date

datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1])

这将计算当月的天数并将其添加到当前日期,使用365/12表示一年的1/12会导致短/长月份的问题(如果您对该日期进行迭代)。

I know this was for 6 months, however the answer shows in google for “adding months in python” if you are adding one month:

import calendar

date = datetime.date.today()    //Or your date

datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1])

this would count the days in the current month and add them to the current date, using 365/12 would ad 1/12 of a year can causes issues for short / long months if your iterating over the date.


回答 8

没有直接的方法可以使用Python的日期时间。

python-dateutil处检查relativedelta类型。它允许您指定以月为单位的时间增量。

There’s no direct way to do it with Python’s datetime.

Check out the relativedelta type at python-dateutil. It allows you to specify a time delta in months.


回答 9

只需使用timetuple方法提取月份,添加月份并构建一个新的dateobject。如果有一个已经存在的方法,我不知道。

import datetime

def in_the_future(months=1):
    year, month, day = datetime.date.today().timetuple()[:3]
    new_month = month + months
    return datetime.date(year + (new_month / 12), (new_month % 12) or 12, day)

该API有点笨拙,但仅作为示例。显然也不适用于2008-01-31 + 1个月等极端情况。:)

Just use the timetuple method to extract the months, add your months and build a new dateobject. If there is a already existing method for this I do not know it.

import datetime

def in_the_future(months=1):
    year, month, day = datetime.date.today().timetuple()[:3]
    new_month = month + months
    return datetime.date(year + (new_month / 12), (new_month % 12) or 12, day)

The API is a bit clumsy, but works as an example. Will also obviously not work on corner-cases like 2008-01-31 + 1 month. :)


回答 10

Dateutil软件包具有此类功能的实现。但是请注意,正如其他人已经指出的那样,这将是幼稚的

Dateutil package has implementation of such functionality. But be aware, that this will be naive, as others pointed already.


回答 11

使用Python标准库(即不使用dateutil或不使用其他库)并解决“ 2月31日”问题:

import datetime
import calendar

def add_months(date, months):
    months_count = date.month + months

    # Calculate the year
    year = date.year + int(months_count / 12)

    # Calculate the month
    month = (months_count % 12)
    if month == 0:
        month = 12

    # Calculate the day
    day = date.day
    last_day_of_month = calendar.monthrange(year, month)[1]
    if day > last_day_of_month:
        day = last_day_of_month

    new_date = datetime.date(year, month, day)
    return new_date

测试:

>>>date = datetime.date(2018, 11, 30)

>>>print(date, add_months(date, 3))
(datetime.date(2018, 11, 30), datetime.date(2019, 2, 28))

>>>print(date, add_months(date, 14))
(datetime.date(2018, 12, 31), datetime.date(2020, 2, 29))

Using Python standard libraries, i.e. without dateutil or others, and solving the ‘February 31st’ problem:

import datetime
import calendar

def add_months(date, months):
    months_count = date.month + months

    # Calculate the year
    year = date.year + int(months_count / 12)

    # Calculate the month
    month = (months_count % 12)
    if month == 0:
        month = 12

    # Calculate the day
    day = date.day
    last_day_of_month = calendar.monthrange(year, month)[1]
    if day > last_day_of_month:
        day = last_day_of_month

    new_date = datetime.date(year, month, day)
    return new_date

Testing:

>>>date = datetime.date(2018, 11, 30)

>>>print(date, add_months(date, 3))
(datetime.date(2018, 11, 30), datetime.date(2019, 2, 28))

>>>print(date, add_months(date, 14))
(datetime.date(2018, 12, 31), datetime.date(2020, 2, 29))

回答 12

我有一个更好的方法来解决“ 2月31日”问题:

def add_months(start_date, months):
    import calendar

    year = start_date.year + (months / 12)
    month = start_date.month + (months % 12)
    day = start_date.day

    if month > 12:
        month = month % 12
        year = year + 1

    days_next = calendar.monthrange(year, month)[1]
    if day > days_next:
        day = days_next

    return start_date.replace(year, month, day)

我认为它也可以使用负数(减去数月),但是我还没有对此进行太多测试。

I have a better way to solve the ‘February 31st’ problem:

def add_months(start_date, months):
    import calendar

    year = start_date.year + (months / 12)
    month = start_date.month + (months % 12)
    day = start_date.day

    if month > 12:
        month = month % 12
        year = year + 1

    days_next = calendar.monthrange(year, month)[1]
    if day > days_next:
        day = days_next

    return start_date.replace(year, month, day)

I think that it also works with negative numbers (to subtract months), but I haven’t tested this very much.


回答 13

PyQt4的QDate类具有addmonths函数。

>>>from PyQt4.QtCore import QDate  
>>>dt = QDate(2009,12,31)  
>>>required = dt.addMonths(6) 

>>>required
PyQt4.QtCore.QDate(2010, 6, 30)

>>>required.toPyDate()
datetime.date(2010, 6, 30)

The QDate class of PyQt4 has an addmonths function.

>>>from PyQt4.QtCore import QDate  
>>>dt = QDate(2009,12,31)  
>>>required = dt.addMonths(6) 

>>>required
PyQt4.QtCore.QDate(2010, 6, 30)

>>>required.toPyDate()
datetime.date(2010, 6, 30)

回答 14

这个怎么样?不使用其他库(dateutil)或timedelta?在vartec的答案的基础上,我做到了,并且我相信它是有效的:

import datetime

today = datetime.date.today()
six_months_from_today = datetime.date(today.year + (today.month + 6)/12, (today.month + 6) % 12, today.day)

我尝试使用timedelta,但是因为它是在计算天数,365/2或者6*356/12并不总是转换为6个月,而是182天。例如

day = datetime.date(2015, 3, 10)
print day
>>> 2015-03-10

print (day + datetime.timedelta(6*365/12))
>>> 2015-09-08

我相信我们通常会假设从某天起的6个月会在该月的同一天,但会在6个月后(即2015-03-10-> 2015-09-10,不是2015-09-08

我希望你觉得这有帮助。

How about this? Not using another library (dateutil) or timedelta? building on vartec‘s answer I did this and I believe it works:

import datetime

today = datetime.date.today()
six_months_from_today = datetime.date(today.year + (today.month + 6)/12, (today.month + 6) % 12, today.day)

I tried using timedelta, but because it is counting the days, 365/2 or 6*356/12 does not always translate to 6 months, but rather 182 days. e.g.

day = datetime.date(2015, 3, 10)
print day
>>> 2015-03-10

print (day + datetime.timedelta(6*365/12))
>>> 2015-09-08

I believe that we usually assume that 6 month’s from a certain day will land on the same day of the month but 6 months later (i.e. 2015-03-10 –> 2015-09-10, Not 2015-09-08)

I hope you find this helpful.


回答 15

这不能回答特定的问题(datetime仅使用),但是,鉴于其他人建议使用不同的模块,此处提供了一个解决方案using pandas

import datetime as dt
import pandas as pd

date = dt.date.today() - \
       pd.offsets.DateOffset(months=6)

print(date)

2019-05-04 00:00:00

在leap年中可以正常工作

date = dt.datetime(2019,8,29) - \
       pd.offsets.DateOffset(months=6)
print(date)

2019-02-28 00:00:00

This doesn’t answer the specific question (using datetime only) but, given that others suggested the use of different modules, here there is a solution using pandas.

import datetime as dt
import pandas as pd

date = dt.date.today() - \
       pd.offsets.DateOffset(months=6)

print(date)

2019-05-04 00:00:00

Which works as expected in leap years

date = dt.datetime(2019,8,29) - \
       pd.offsets.DateOffset(months=6)
print(date)

2019-02-28 00:00:00

回答 16

修改了AddMonths()以在Zope中使用并处理无效的天数:

def AddMonths(d,x):
    days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    newmonth = ((( d.month() - 1) + x ) % 12 ) + 1
    newyear  = d.year() + ((( d.month() - 1) + x ) // 12 ) 
    if d.day() > days_of_month[newmonth-1]:
      newday = days_of_month[newmonth-1]
    else:
      newday = d.day() 
    return DateTime( newyear, newmonth, newday)

Modified the AddMonths() for use in Zope and handling invalid day numbers:

def AddMonths(d,x):
    days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    newmonth = ((( d.month() - 1) + x ) % 12 ) + 1
    newyear  = d.year() + ((( d.month() - 1) + x ) // 12 ) 
    if d.day() > days_of_month[newmonth-1]:
      newday = days_of_month[newmonth-1]
    else:
      newday = d.day() 
    return DateTime( newyear, newmonth, newday)

回答 17

import time

def add_month(start_time, months):  

        ret = time.strptime(start_time, '%Y-%m-%d')
        t = list(ret)

        t[1] += months

        if t[1] > 12:
            t[0] += 1 + int(months / 12)

            t[1] %= 12

        return int(time.mktime(tuple(t)))
import time

def add_month(start_time, months):  

        ret = time.strptime(start_time, '%Y-%m-%d')
        t = list(ret)

        t[1] += months

        if t[1] > 12:
            t[0] += 1 + int(months / 12)

            t[1] %= 12

        return int(time.mktime(tuple(t)))

回答 18

import datetime


'''
Created on 2011-03-09

@author: tonydiep
'''

def add_business_months(start_date, months_to_add):
    """
    Add months in the way business people think of months. 
    Jan 31, 2011 + 1 month = Feb 28, 2011 to business people
    Method: Add the number of months, roll back the date until it becomes a valid date
    """
    # determine year
    years_change = months_to_add / 12

    # determine if there is carryover from adding months
    if (start_date.month + (months_to_add % 12) > 12 ):
        years_change = years_change + 1

    new_year = start_date.year + years_change

    # determine month
    work = months_to_add % 12
    if 0 == work:
        new_month = start_date.month
    else:
        new_month = (start_date.month + (work % 12)) % 12

    if 0 == new_month:
        new_month = 12 

    # determine day of the month
    new_day = start_date.day
    if(new_day in [31, 30, 29, 28]):
        #user means end of the month
        new_day = 31


    new_date = None
    while (None == new_date and 27 < new_day):
        try:
            new_date = start_date.replace(year=new_year, month=new_month, day=new_day)
        except:
            new_day = new_day - 1   #wind down until we get to a valid date

    return new_date


if __name__ == '__main__':
    #tests
    dates = [datetime.date(2011, 1, 31),
             datetime.date(2011, 2, 28),
             datetime.date(2011, 3, 28),
             datetime.date(2011, 4, 28),
             datetime.date(2011, 5, 28),
             datetime.date(2011, 6, 28),
             datetime.date(2011, 7, 28),
             datetime.date(2011, 8, 28),
             datetime.date(2011, 9, 28),
             datetime.date(2011, 10, 28),
             datetime.date(2011, 11, 28),
             datetime.date(2011, 12, 28),
             ]
    months = range(1, 24)
    for start_date in dates:
        for m in months:
            end_date = add_business_months(start_date, m)
            print("%s\t%s\t%s" %(start_date, end_date, m))
import datetime


'''
Created on 2011-03-09

@author: tonydiep
'''

def add_business_months(start_date, months_to_add):
    """
    Add months in the way business people think of months. 
    Jan 31, 2011 + 1 month = Feb 28, 2011 to business people
    Method: Add the number of months, roll back the date until it becomes a valid date
    """
    # determine year
    years_change = months_to_add / 12

    # determine if there is carryover from adding months
    if (start_date.month + (months_to_add % 12) > 12 ):
        years_change = years_change + 1

    new_year = start_date.year + years_change

    # determine month
    work = months_to_add % 12
    if 0 == work:
        new_month = start_date.month
    else:
        new_month = (start_date.month + (work % 12)) % 12

    if 0 == new_month:
        new_month = 12 

    # determine day of the month
    new_day = start_date.day
    if(new_day in [31, 30, 29, 28]):
        #user means end of the month
        new_day = 31


    new_date = None
    while (None == new_date and 27 < new_day):
        try:
            new_date = start_date.replace(year=new_year, month=new_month, day=new_day)
        except:
            new_day = new_day - 1   #wind down until we get to a valid date

    return new_date


if __name__ == '__main__':
    #tests
    dates = [datetime.date(2011, 1, 31),
             datetime.date(2011, 2, 28),
             datetime.date(2011, 3, 28),
             datetime.date(2011, 4, 28),
             datetime.date(2011, 5, 28),
             datetime.date(2011, 6, 28),
             datetime.date(2011, 7, 28),
             datetime.date(2011, 8, 28),
             datetime.date(2011, 9, 28),
             datetime.date(2011, 10, 28),
             datetime.date(2011, 11, 28),
             datetime.date(2011, 12, 28),
             ]
    months = range(1, 24)
    for start_date in dates:
        for m in months:
            end_date = add_business_months(start_date, m)
            print("%s\t%s\t%s" %(start_date, end_date, m))

回答 19

在1new_month = 121的情况下修改了Johannes Wei的答案。这对我来说非常有效。月份可以是正数或负数。

def addMonth(d,months=1):
    year, month, day = d.timetuple()[:3]
    new_month = month + months
    return datetime.date(year + ((new_month-1) / 12), (new_month-1) % 12 +1, day)

Modified Johannes Wei’s answer in the case 1new_month = 121. This works perfectly for me. The months could be positive or negative.

def addMonth(d,months=1):
    year, month, day = d.timetuple()[:3]
    new_month = month + months
    return datetime.date(year + ((new_month-1) / 12), (new_month-1) % 12 +1, day)

回答 20

另一个解决方案-希望有人会喜欢它:

def add_months(d, months):
    return d.replace(year=d.year+months//12).replace(month=(d.month+months)%12)

此解决方案在所有情况下都无法正常工作29,30,31天,因此需要更强大的解决方案(现在不再那么好了:)):

def add_months(d, months):
    for i in range(4):
        day = d.day - i
        try:
            return d.replace(day=day).replace(year=d.year+int(months)//12).replace(month=(d.month+int(months))%12)
        except:
            pass
    raise Exception("should not happen")

Yet another solution – hope someone will like it:

def add_months(d, months):
    return d.replace(year=d.year+months//12).replace(month=(d.month+months)%12)

This solution doesn’t work for days 29,30,31 for all cases, so more robust solution is needed (which is not so nice anymore :) ):

def add_months(d, months):
    for i in range(4):
        day = d.day - i
        try:
            return d.replace(day=day).replace(year=d.year+int(months)//12).replace(month=(d.month+int(months))%12)
        except:
            pass
    raise Exception("should not happen")

回答 21

这个答案,看到parsedatetime。代码示例如下。更多详细信息:单元测试包含许多自然语言-> YYYY-MM-DD转换示例,以及明显的parsedatetime转换挑战/错误

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time, calendar
from datetime import date

# from https://github.com/bear/parsedatetime
import parsedatetime as pdt

def print_todays_date():
    todays_day_of_week = calendar.day_name[date.today().weekday()]
    print "today's date = " + todays_day_of_week + ', ' + \
                              time.strftime('%Y-%m-%d')

def convert_date(natural_language_date):
    cal = pdt.Calendar()
    (struct_time_date, success) = cal.parse(natural_language_date)
    if success:
        formal_date = time.strftime('%Y-%m-%d', struct_time_date)
    else:
        formal_date = '(conversion failed)'
    print '{0:12s} -> {1:10s}'.format(natural_language_date, formal_date)

print_todays_date()
convert_date('6 months')

上面的代码从MacOSX计算机生成以下代码:

$ ./parsedatetime_simple.py 
today's date = Wednesday, 2015-05-13
6 months     -> 2015-11-13
$ 

From this answer, see parsedatetime. Code example follows. More details: unit test with many natural-language -> YYYY-MM-DD conversion examples, and apparent parsedatetime conversion challenges/bugs.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time, calendar
from datetime import date

# from https://github.com/bear/parsedatetime
import parsedatetime as pdt

def print_todays_date():
    todays_day_of_week = calendar.day_name[date.today().weekday()]
    print "today's date = " + todays_day_of_week + ', ' + \
                              time.strftime('%Y-%m-%d')

def convert_date(natural_language_date):
    cal = pdt.Calendar()
    (struct_time_date, success) = cal.parse(natural_language_date)
    if success:
        formal_date = time.strftime('%Y-%m-%d', struct_time_date)
    else:
        formal_date = '(conversion failed)'
    print '{0:12s} -> {1:10s}'.format(natural_language_date, formal_date)

print_todays_date()
convert_date('6 months')

The above code generates the following from a MacOSX machine:

$ ./parsedatetime_simple.py 
today's date = Wednesday, 2015-05-13
6 months     -> 2015-11-13
$ 

回答 22

这是一个示例,它使用户可以决定如何返回日期大于月份中天数的日期。

def add_months(date, months, endOfMonthBehaviour='RoundUp'):
    assert endOfMonthBehaviour in ['RoundDown', 'RoundIn', 'RoundOut', 'RoundUp'], \
        'Unknown end of month behaviour'
    year = date.year + (date.month + months - 1) / 12
    month = (date.month + months - 1) % 12 + 1
    day = date.day
    last = monthrange(year, month)[1]
    if day > last:
        if endOfMonthBehaviour == 'RoundDown' or \
            endOfMonthBehaviour == 'RoundOut' and months < 0 or \
            endOfMonthBehaviour == 'RoundIn' and months > 0:
            day = last
        elif endOfMonthBehaviour == 'RoundUp' or \
            endOfMonthBehaviour == 'RoundOut' and months > 0 or \
            endOfMonthBehaviour == 'RoundIn' and months < 0:
            # we don't need to worry about incrementing the year
            # because there will never be a day in December > 31
            month += 1
            day = 1
    return datetime.date(year, month, day)


>>> from calendar import monthrange
>>> import datetime
>>> add_months(datetime.datetime(2016, 1, 31), 1)
datetime.date(2016, 3, 1)
>>> add_months(datetime.datetime(2016, 1, 31), -2)
datetime.date(2015, 12, 1)
>>> add_months(datetime.datetime(2016, 1, 31), -2, 'RoundDown')
datetime.date(2015, 11, 30)

Here’s a example which allows the user to decide how to return a date where the day is greater than the number of days in the month.

def add_months(date, months, endOfMonthBehaviour='RoundUp'):
    assert endOfMonthBehaviour in ['RoundDown', 'RoundIn', 'RoundOut', 'RoundUp'], \
        'Unknown end of month behaviour'
    year = date.year + (date.month + months - 1) / 12
    month = (date.month + months - 1) % 12 + 1
    day = date.day
    last = monthrange(year, month)[1]
    if day > last:
        if endOfMonthBehaviour == 'RoundDown' or \
            endOfMonthBehaviour == 'RoundOut' and months < 0 or \
            endOfMonthBehaviour == 'RoundIn' and months > 0:
            day = last
        elif endOfMonthBehaviour == 'RoundUp' or \
            endOfMonthBehaviour == 'RoundOut' and months > 0 or \
            endOfMonthBehaviour == 'RoundIn' and months < 0:
            # we don't need to worry about incrementing the year
            # because there will never be a day in December > 31
            month += 1
            day = 1
    return datetime.date(year, month, day)


>>> from calendar import monthrange
>>> import datetime
>>> add_months(datetime.datetime(2016, 1, 31), 1)
datetime.date(2016, 3, 1)
>>> add_months(datetime.datetime(2016, 1, 31), -2)
datetime.date(2015, 12, 1)
>>> add_months(datetime.datetime(2016, 1, 31), -2, 'RoundDown')
datetime.date(2015, 11, 30)

回答 23

假设您的datetime变量称为date:

date=datetime.datetime(year=date.year+int((date.month+6)/12),
                       month=(date.month+6)%13 + (1 if (date.month + 
                       months>12) else 0), day=date.day)

given that your datetime variable is called date:

date=datetime.datetime(year=date.year+int((date.month+6)/12),
                       month=(date.month+6)%13 + (1 if (date.month + 
                       months>12) else 0), day=date.day)

回答 24

获取x个月之后/之前的下一个日期的常规功能。

从日期时间导入日期

def after_month(给定日期,月份):
    yyyy = int((((给定日期。年* 12 +给定日期。月)+月)/ 12)
    mm = int((((给定日期。年* 12 +给定日期。月)+月)%12)

    如果mm == 0:
        yyyy-= 1
        毫米= 12
    返回给定的date.replace(年= yyyy,月= mm)


如果__name__ ==“ __main__”:
    今天= date.today()
    打印(今天)

    对于[-12,-1,0,1,2,12,20]中的mm:
        next_date = after_month(今天,毫米)
        打印(下一个日期)

General function to get next date after/before x months.

from datetime import date

def after_month(given_date, month):
    yyyy = int(((given_date.year * 12 + given_date.month) + month)/12)
    mm = int(((given_date.year * 12 + given_date.month) + month)%12)

    if mm == 0:
        yyyy -= 1
        mm = 12
    return given_date.replace(year=yyyy, month=mm)


if __name__ == "__main__":
    today = date.today()
    print(today)

    for mm in [-12, -1, 0, 1, 2, 12, 20 ]:
        next_date = after_month(today, mm)
        print(next_date)

回答 25

一个快速的建议是箭头

点安装箭头

>>> import arrow

>>> arrow.now().date()
datetime.date(2019, 6, 28)
>>> arrow.now().shift(months=6).date()
datetime.date(2019, 12, 28)

A quick suggestion is Arrow

pip install arrow

>>> import arrow

>>> arrow.now().date()
datetime.date(2019, 6, 28)
>>> arrow.now().shift(months=6).date()
datetime.date(2019, 12, 28)

回答 26

使用python datetime模块将六个月的时间增量添加到datetime.today()。

http://docs.python.org/library/datetime.html

当然,你将要解决什么约翰内斯Weiß–提出的问题你6个月意味着什么呢?

Use the python datetime module to add a timedelta of six months to datetime.today() .

http://docs.python.org/library/datetime.html

You will of course have to solve the issue raised by Johannes Weiß– what do you mean by 6 months?


回答 27

这就是我想出的。它可以移动正确的月数和年数,但会忽略天数(这是我当时所需要的)。

import datetime

month_dt = 4
today = datetime.date.today()
y,m = today.year, today.month
m += month_dt-1
year_dt = m//12
new_month = m%12
new_date = datetime.date(y+year_dt, new_month+1, 1)

This is what I came up with. It moves the correct number of months and years but ignores days (which was what I needed in my situation).

import datetime

month_dt = 4
today = datetime.date.today()
y,m = today.year, today.month
m += month_dt-1
year_dt = m//12
new_month = m%12
new_date = datetime.date(y+year_dt, new_month+1, 1)

回答 28

我使用此功能更改年份和月份,但保留日期:

def replace_month_year(date1, year2, month2):
    try:
        date2 = date1.replace(month = month2, year = year2)
    except:
        date2 = datetime.date(year2, month2 + 1, 1) - datetime.timedelta(days=1)
    return date2

您应该写:

new_year = my_date.year + (my_date.month + 6) / 12
new_month = (my_date.month + 6) % 12
new_date = replace_month_year(my_date, new_year, new_month)

I use this function to change year and month but keep day:

def replace_month_year(date1, year2, month2):
    try:
        date2 = date1.replace(month = month2, year = year2)
    except:
        date2 = datetime.date(year2, month2 + 1, 1) - datetime.timedelta(days=1)
    return date2

You should write:

new_year = my_date.year + (my_date.month + 6) / 12
new_month = (my_date.month + 6) % 12
new_date = replace_month_year(my_date, new_year, new_month)

回答 29

我认为这样做比手动添加天数更安全:

import datetime
today = datetime.date.today()

def addMonths(dt, months = 0):
    new_month = months + dt.month
    year_inc = 0
    if new_month>12:
        year_inc +=1
        new_month -=12
    return dt.replace(month = new_month, year = dt.year+year_inc)

newdate = addMonths(today, 6)

I think it would be safer to do something like this instead of manually adding days:

import datetime
today = datetime.date.today()

def addMonths(dt, months = 0):
    new_month = months + dt.month
    year_inc = 0
    if new_month>12:
        year_inc +=1
        new_month -=12
    return dt.replace(month = new_month, year = dt.year+year_inc)

newdate = addMonths(today, 6)

将Unix时间戳字符串转换为可读日期

问题:将Unix时间戳字符串转换为可读日期

我有一个表示Python中的unix时间戳的字符串(即“ 1284101485”),我想将其转换为可读的日期。使用时time.strftime,我得到TypeError

>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str

I have a string representing a unix timestamp (i.e. “1284101485”) in Python, and I’d like to convert it to a readable date. When I use time.strftime, I get a TypeError:

>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str

回答 0

使用datetime模块:

from datetime import datetime
ts = int("1284101485")

# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

Use datetime module:

from datetime import datetime
ts = int("1284101485")

# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

回答 1

>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

取自http://seehuhn.de/pages/pdate

>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

Taken from http://seehuhn.de/pages/pdate


回答 2

投票最多的答案建议使用fromtimestamp,因为它使用本地时区,因此容易出错。为了避免出现问题,更好的方法是使用UTC:

datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')

其中posix_time是要转换的Posix纪元时间

The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC:

datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')

Where posix_time is the Posix epoch time you want to convert


回答 3

>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'
>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'

回答 4

有两个部分:

  1. 将Unix时间戳(“自纪元以来的秒数”)转换为本地时间
  2. 以所需格式显示当地时间。

即使本地时区过去有不同的utc偏移并且python无法访问tz数据库,获取本地时间有效的一种便携式方法是使用pytz时区:

#!/usr/bin/env python
from datetime import datetime
import tzlocal  # $ pip install tzlocal

unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)

要显示它,您可以使用系统支持的任何时间格式,例如:

print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y"))  # print date in your format

如果您不需要当地时间,请改为获取可读的UTC时间:

utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))

如果您不关心可能影响返回日期的时区问题,或者python是否有权访问系统上的tz数据库:

local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))

在Python 3上,您可以仅使用stdlib获得时区感知日期时间(如果python无法访问系统上的tz数据库,例如Windows上的UTC偏移量可能是错误的):

#!/usr/bin/env python3
from datetime import datetime, timezone

utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))

time模块中的函数是对应C API的薄包装,因此它们可能比对应datetime方法的可移植性差,否则您也可以使用它们:

#!/usr/bin/env python
import time

unix_timestamp  = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time)) 
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))  

There are two parts:

  1. Convert the unix timestamp (“seconds since epoch”) to the local time
  2. Display the local time in the desired format.

A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a pytz timezone:

#!/usr/bin/env python
from datetime import datetime
import tzlocal  # $ pip install tzlocal

unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)

To display it, you could use any time format that is supported by your system e.g.:

print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y"))  # print date in your format

If you do not need a local time, to get a readable UTC time instead:

utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))

If you don’t care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system:

local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))

On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows):

#!/usr/bin/env python3
from datetime import datetime, timezone

utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))

Functions from the time module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding datetime methods otherwise you could use them too:

#!/usr/bin/env python
import time

unix_timestamp  = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time)) 
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))  

回答 5

为了使UNIX时间戳易于理解,我以前在脚本中使用过它:

import os, datetime

datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")

输出:

‘2012年12月26日’

For a human readable timestamp from a UNIX timestamp, I have used this in scripts before:

import os, datetime

datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")

Output:

‘December 26, 2012’


回答 6

您可以像这样转换当前时间

t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'

将字符串中的日期转换为其他格式。

import datetime,time

def createDateObject(str_date,strFormat="%Y-%m-%d"):    
    timeStamp = time.mktime(time.strptime(str_date,strFormat))
    return datetime.datetime.fromtimestamp(timeStamp)

def FormatDate(objectDate,strFormat="%Y-%m-%d"):
    return objectDate.strftime(strFormat)

Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')

Output 03-03-2013

You can convert the current time like this

t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'

To convert a date in string to different formats.

import datetime,time

def createDateObject(str_date,strFormat="%Y-%m-%d"):    
    timeStamp = time.mktime(time.strptime(str_date,strFormat))
    return datetime.datetime.fromtimestamp(timeStamp)

def FormatDate(objectDate,strFormat="%Y-%m-%d"):
    return objectDate.strftime(strFormat)

Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')

Output 03-03-2013

回答 7

除了使用time / datetime包之外,pandas还可以用于解决相同的问题。这是我们可以使用pandas时间戳转换为可读日期的方法

时间戳可以有两种格式:

  1. 13位数字(毫秒)-要将毫秒转换日期,请使用:

    import pandas
    result_ms=pandas.to_datetime('1493530261000',unit='ms')
    str(result_ms)
    
    Output: '2017-04-30 05:31:01'
  2. 10位(秒)-要将转换为日期,请使用:

    import pandas
    result_s=pandas.to_datetime('1493530261',unit='s')
    str(result_s)
    
    Output: '2017-04-30 05:31:01'

Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:

Timestamps can be in two formats:

  1. 13 digits(milliseconds) – To convert milliseconds to date, use:

    import pandas
    result_ms=pandas.to_datetime('1493530261000',unit='ms')
    str(result_ms)
    
    Output: '2017-04-30 05:31:01'
    
  2. 10 digits(seconds) – To convert seconds to date, use:

    import pandas
    result_s=pandas.to_datetime('1493530261',unit='s')
    str(result_s)
    
    Output: '2017-04-30 05:31:01'
    

回答 8

timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')

您还可以从时间戳获取带有时间的可读日期,也可以更改日期格式。

timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')

Get the readable date from timestamp with time also, also you can change the format of the date.


回答 9

在Python 3.6+中:

import datetime

timestamp = 1579117901
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")

输出:

2020-01-15 19:51:41

说明:

In Python 3.6+:

import datetime

timestamp = 1579117901
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")

Output:

2020-01-15 19:51:41

Explanation:


回答 10

import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp
import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp

回答 11

可以使用gmtime和format函数完成此操作的另一种方法;

from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))

输出: 2018-10-4 11:57:44

Another way that this can be done using gmtime and format function;

from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))

Output: 2018-10-4 11:57:44


回答 12

我刚刚成功使用过:

>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date

i just successfully used:

>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date

回答 13

快速又脏的一个衬里:

'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))

‘2013-5-5-1-9-43’

quick and dirty one liner:

'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))

‘2013-5-5-1-9-43’


回答 14

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

import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")

You can use easy_date to make it easy:

import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")