标签归档:datetime

如何自定义Python日志记录的时间格式?

问题:如何自定义Python日志记录的时间格式?

我是Python日志记录包的新手,并计划将其用于我的项目。我想根据自己的喜好定制时间格式。这是我从教程中复制的简短代码:

import logging

# create logger
logger = logging.getLogger("logging_tryout2")
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

这是输出:

2010-07-10 10:46:28,811;DEBUG;debug message
2010-07-10 10:46:28,812;INFO;info message
2010-07-10 10:46:28,812;WARNING;warn message
2010-07-10 10:46:28,812;ERROR;error message
2010-07-10 10:46:28,813;CRITICAL;critical message

我想将时间格式缩短为:“ 2010-07-10 10:46:28”,删除毫秒后缀。我看着Formatter.formatTime,但是很困惑。感谢您为实现我的目标所提供的帮助。谢谢。

I am new to Python’s logging package and plan to use it for my project. I would like to customize the time format to my taste. Here is a short code I copied from a tutorial:

import logging

# create logger
logger = logging.getLogger("logging_tryout2")
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

And here is the output:

2010-07-10 10:46:28,811;DEBUG;debug message
2010-07-10 10:46:28,812;INFO;info message
2010-07-10 10:46:28,812;WARNING;warn message
2010-07-10 10:46:28,812;ERROR;error message
2010-07-10 10:46:28,813;CRITICAL;critical message

I would like to shorten the time format to just: ‘2010-07-10 10:46:28‘, dropping the mili-second suffix. I looked at the Formatter.formatTime, but confused. I appreciate your help to achieve my goal. Thank you.


回答 0

从有关Formatter类的官方文档中

构造函数采用两个可选参数:消息格式字符串和日期格式字符串。

所以改变

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")

From the official documentation regarding the Formatter class:

The constructor takes two optional arguments: a message format string and a date format string.

So change

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

to

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")

回答 1

使用logging.basicConfig,以下示例对我有用:

logging.basicConfig(
    filename='HISTORYlistener.log',
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
)

这样一来,您就可以全部格式化和配置文件。生成的日志记录如下所示:

2014-05-26 12:22:52.376 CRITICAL historylistener - main: History log failed to start

Using logging.basicConfig, the following example works for me:

logging.basicConfig(
    filename='HISTORYlistener.log',
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
)

This allows you to format & config all in one line. A resulting log record looks as follows:

2014-05-26 12:22:52.376 CRITICAL historylistener - main: History log failed to start

回答 2

如果将logging.config.fileConfig与配置文件一起使用,请使用以下内容:

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

if using logging.config.fileConfig with a configuration file use something like:

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

回答 3

为了增加其他答案,这是Python文档中的变量列表

Directive   Meaning Notes

%a  Locales abbreviated weekday name.   
%A  Locales full weekday name.  
%b  Locales abbreviated month name.     
%B  Locales full month name.    
%c  Locales appropriate date and time representation.   
%d  Day of the month as a decimal number [01,31].    
%H  Hour (24-hour clock) as a decimal number [00,23].    
%I  Hour (12-hour clock) as a decimal number [01,12].    
%j  Day of the year as a decimal number [001,366].   
%m  Month as a decimal number [01,12].   
%M  Minute as a decimal number [00,59].  
%p  Locales equivalent of either AM or PM. (1)
%S  Second as a decimal number [00,61]. (2)
%U  Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.    (3)
%w  Weekday as a decimal number [0(Sunday),6].   
%W  Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.    (3)
%x  Locales appropriate date representation.    
%X  Locales appropriate time representation.    
%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.   
%z  Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
%Z  Time zone name (no characters if no time zone exists).   
%%  A literal '%' character.     

To add to the other answers, here are the variable list from Python Documentation.

Directive   Meaning Notes

%a  Locale’s abbreviated weekday name.   
%A  Locale’s full weekday name.  
%b  Locale’s abbreviated month name.     
%B  Locale’s full month name.    
%c  Locale’s appropriate date and time representation.   
%d  Day of the month as a decimal number [01,31].    
%H  Hour (24-hour clock) as a decimal number [00,23].    
%I  Hour (12-hour clock) as a decimal number [01,12].    
%j  Day of the year as a decimal number [001,366].   
%m  Month as a decimal number [01,12].   
%M  Minute as a decimal number [00,59].  
%p  Locale’s equivalent of either AM or PM. (1)
%S  Second as a decimal number [00,61]. (2)
%U  Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.    (3)
%w  Weekday as a decimal number [0(Sunday),6].   
%W  Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.    (3)
%x  Locale’s appropriate date representation.    
%X  Locale’s appropriate time representation.    
%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.   
%z  Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
%Z  Time zone name (no characters if no time zone exists).   
%%  A literal '%' character.     

用Python方式添加datetime.date和datetime.time对象

问题:用Python方式添加datetime.date和datetime.time对象

我有两个代表同一事件实例的对象-一个保存日期,另一个保存该事件的时间,我想创建一个datetime对象。

由于不能简单地添加日期和时间对象(以下调用失败):

 datetime.date(2011, 01, 01) + datetime.time(10, 23)

I have two objects that represent the same event instance — one holds the date, the other the time of this event, and I want to create a datetime object.

Since one can’t simply add date and time objects (following call fails):

 datetime.date(2011, 01, 01) + datetime.time(10, 23)

回答 0

python docs中

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

退货

datetime.datetime(2011, 1, 1, 10, 23)

It’s in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

如何将整数时间戳转换为Python日期时间

问题:如何将整数时间戳转换为Python日期时间

我有一个数据文件,包含“ 1331856000000”之类的时间戳。不幸的是,我没有太多有关该格式的文档,所以我不确定时间戳的格式。我已经尝试了Python的标准datetime.fromordinal()datetime.fromtimestamp()其他一些标准,但是没有任何匹配。我很确定特定数字对应于当前日期(例如2012-3-16),但不多。

如何将此数字转换为datetime

I have a data file containing timestamps like “1331856000000”. Unfortunately, I don’t have a lot of documentation for the format, so I’m not sure how the timestamp is formatted. I’ve tried Python’s standard datetime.fromordinal() and datetime.fromtimestamp() and a few others, but nothing matches. I’m pretty sure that particular number corresponds to the current date (e.g. 2012-3-16), but not much more.

How do I convert this number to a datetime?


回答 0

datetime.datetime.fromtimestamp()是正确的,除了您的时间戳可能以毫秒为单位(例如在JavaScript中),但fromtimestamp()希望Unix时间戳以秒为单位。

那样做:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

结果是:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

它能回答您的问题吗?

编辑:JF塞巴斯蒂安正确建议使用真司1e3(浮动1000)。如果您想获得精确的结果,则差异非常明显,因此我更改了答案。所不同的结果在Python 2.x中的默认行为,它总是返回int分(当使用/运营商)intint(这就是所谓的地板事业部)。通过更换除数1000(作为一个int与所述)1e3除数(即的表示1000为float)或用float(1000)(或1000.等),分割变得真正分裂。的Python 2.x的收益float除以时int通过floatfloat通过intfloatfloat等而当在传递到时间戳一些小数部分fromtimestamp()的方法,该方法的结果也包含有关该小数部分的信息(如微秒的数量)。

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method’s result also contains information about that fractional part (as the number of microseconds).


仅使用python标准库将python UTC日期时间转换为本地日期时间?

问题:仅使用python标准库将python UTC日期时间转换为本地日期时间?

我有一个使用datetime.utcnow()创建并保存在数据库中的python datetime实例。

为了进行显示,我想使用默认的本地时区(例如,好像使用datetime.now()创建了datetime)将从数据库中检索到的datetime实例转换为本地datetime。

如何仅使用python标准库(例如,没有pytz依赖项)将UTC日期时间转换为本地日期时间?

似乎一种解决方案是使用datetime.astimezone(tz),但是如何获得默认的本地时区?

I have a python datetime instance that was created using datetime.utcnow() and persisted in database.

For display, I would like to convert the datetime instance retrieved from the database to local datetime using the default local timezone (i.e., as if the datetime was created using datetime.now()).

How can I convert the UTC datetime to a local datetime using only python standard library (e.g., no pytz dependency)?

It seems one solution would be to use datetime.astimezone( tz ), but how would you get the default local timezone?


回答 0

在Python 3.3+中:

from datetime import datetime, timezone

def utc_to_local(utc_dt):
    return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)

在Python 2/3中:

import calendar
from datetime import datetime, timedelta

def utc_to_local(utc_dt):
    # get integer timestamp to avoid precision lost
    timestamp = calendar.timegm(utc_dt.timetuple())
    local_dt = datetime.fromtimestamp(timestamp)
    assert utc_dt.resolution >= timedelta(microseconds=1)
    return local_dt.replace(microsecond=utc_dt.microsecond)

使用pytz(两个Python 2/3):

import pytz

local_tz = pytz.timezone('Europe/Moscow') # use your local timezone name here
# NOTE: pytz.reference.LocalTimezone() would produce wrong result here

## You could use `tzlocal` module to get local timezone on Unix and Win32
# from tzlocal import get_localzone # $ pip install tzlocal

# # get local timezone    
# local_tz = get_localzone()

def utc_to_local(utc_dt):
    local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
    return local_tz.normalize(local_dt) # .normalize might be unnecessary

def aslocaltimestr(utc_dt):
    return utc_to_local(utc_dt).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z')

print(aslocaltimestr(datetime(2010,  6, 6, 17, 29, 7, 730000)))
print(aslocaltimestr(datetime(2010, 12, 6, 17, 29, 7, 730000)))
print(aslocaltimestr(datetime.utcnow()))

输出量

Python 3.3
2010-06-06 21:29:07.730000 MSD+0400
2010-12-06 20:29:07.730000 MSK+0300
2012-11-08 14:19:50.093745 MSK+0400
Python 2
2010-06-06 21:29:07.730000 
2010-12-06 20:29:07.730000 
2012-11-08 14:19:50.093911 
pytz
2010-06-06 21:29:07.730000 MSD+0400
2010-12-06 20:29:07.730000 MSK+0300
2012-11-08 14:19:50.146917 MSK+0400

注意:它考虑了DST和MSK时区的utc偏移量的最新变化。

我不知道非pytz解决方案是否可以在Windows上运行。

In Python 3.3+:

from datetime import datetime, timezone

def utc_to_local(utc_dt):
    return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)

In Python 2/3:

import calendar
from datetime import datetime, timedelta

def utc_to_local(utc_dt):
    # get integer timestamp to avoid precision lost
    timestamp = calendar.timegm(utc_dt.timetuple())
    local_dt = datetime.fromtimestamp(timestamp)
    assert utc_dt.resolution >= timedelta(microseconds=1)
    return local_dt.replace(microsecond=utc_dt.microsecond)

Using pytz (both Python 2/3):

import pytz

local_tz = pytz.timezone('Europe/Moscow') # use your local timezone name here
# NOTE: pytz.reference.LocalTimezone() would produce wrong result here

## You could use `tzlocal` module to get local timezone on Unix and Win32
# from tzlocal import get_localzone # $ pip install tzlocal

# # get local timezone    
# local_tz = get_localzone()

def utc_to_local(utc_dt):
    local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
    return local_tz.normalize(local_dt) # .normalize might be unnecessary

Example

def aslocaltimestr(utc_dt):
    return utc_to_local(utc_dt).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z')

print(aslocaltimestr(datetime(2010,  6, 6, 17, 29, 7, 730000)))
print(aslocaltimestr(datetime(2010, 12, 6, 17, 29, 7, 730000)))
print(aslocaltimestr(datetime.utcnow()))

Output

Python 3.3
2010-06-06 21:29:07.730000 MSD+0400
2010-12-06 20:29:07.730000 MSK+0300
2012-11-08 14:19:50.093745 MSK+0400
Python 2
2010-06-06 21:29:07.730000 
2010-12-06 20:29:07.730000 
2012-11-08 14:19:50.093911 
pytz
2010-06-06 21:29:07.730000 MSD+0400
2010-12-06 20:29:07.730000 MSK+0300
2012-11-08 14:19:50.146917 MSK+0400

Note: it takes into account DST and the recent change of utc offset for MSK timezone.

I don’t know whether non-pytz solutions work on Windows.


回答 1

您不能仅使用标准库来执行此操作,因为标准库没有任何时区。您需要pytzdateutil

>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> from dateutil import tz
>>> HERE = tz.tzlocal()
>>> UTC = tz.gettz('UTC')

The Conversion:
>>> gmt = now.replace(tzinfo=UTC)
>>> gmt.astimezone(HERE)
datetime.datetime(2010, 12, 30, 15, 51, 22, 114668, tzinfo=tzlocal())

或者,可以通过实现自己的时区来实现,而无需pytz或dateutil。但这将是愚蠢的。

You can’t do it with only the standard library as the standard library doesn’t have any timezones. You need pytz or dateutil.

>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> from dateutil import tz
>>> HERE = tz.tzlocal()
>>> UTC = tz.gettz('UTC')

The Conversion:
>>> gmt = now.replace(tzinfo=UTC)
>>> gmt.astimezone(HERE)
datetime.datetime(2010, 12, 30, 15, 51, 22, 114668, tzinfo=tzlocal())

Or well, you can do it without pytz or dateutil by implementing your own timezones. But that would be silly.


回答 2

您无法使用标准库执行此操作。使用 pytz模块,您可以将任何原始/知道的datetime对象转换为任何其他时区。让我们来看一些使用Python 3的示例。

通过类方法创建的幼稚对象 utcnow()

要将原始对象转换为任何其他时区,首先必须将其转换为可感知的日期时间对象。您可以使用replace一个转换方法天真的 DateTime对象的感知 DateTime对象。然后到转换意识到 DateTime对象,你可以使用任何其它时区astimezone的方法。

该变量pytz.all_timezones为您提供pytz模块中所有可用时区的列表。

import datetime,pytz

dtobj1=datetime.datetime.utcnow()   #utcnow class method
print(dtobj1)

dtobj3=dtobj1.replace(tzinfo=pytz.UTC) #replace method

dtobj_hongkong=dtobj3.astimezone(pytz.timezone("Asia/Hong_Kong")) #astimezone method
print(dtobj_hongkong)

通过类方法创建的幼稚对象 now()

因为nowmethod返回当前日期和时间,所以您必须首先使datetime对象时区知道。该localize 函数将天真日期时间对象转换为时区感知日期时间对象。然后,您可以使用该astimezone方法将其转换为另一个时区。

dtobj2=datetime.datetime.now()

mytimezone=pytz.timezone("Europe/Vienna") #my current timezone
dtobj4=mytimezone.localize(dtobj2)        #localize function

dtobj_hongkong=dtobj4.astimezone(pytz.timezone("Asia/Hong_Kong")) #astimezone method
print(dtobj_hongkong)

You can’t do it with standard library. Using pytz module you can convert any naive/aware datetime object to any other time zone. Lets see some examples using Python 3.

Naive objects created through class method utcnow()

To convert a naive object to any other time zone, first you have to convert it into aware datetime object. You can use the replace method for converting a naive datetime object to an aware datetime object. Then to convert an aware datetime object to any other timezone you can use astimezone method.

The variable pytz.all_timezones gives you the list of all available time zones in pytz module.

import datetime,pytz

dtobj1=datetime.datetime.utcnow()   #utcnow class method
print(dtobj1)

dtobj3=dtobj1.replace(tzinfo=pytz.UTC) #replace method

dtobj_hongkong=dtobj3.astimezone(pytz.timezone("Asia/Hong_Kong")) #astimezone method
print(dtobj_hongkong)

Naive objects created through class method now()

Because now method returns current date and time, so you have to make the datetime object timezone aware first. The localize function converts a naive datetime object into a timezone-aware datetime object. Then you can use the astimezone method to convert it into another timezone.

dtobj2=datetime.datetime.now()

mytimezone=pytz.timezone("Europe/Vienna") #my current timezone
dtobj4=mytimezone.localize(dtobj2)        #localize function

dtobj_hongkong=dtobj4.astimezone(pytz.timezone("Asia/Hong_Kong")) #astimezone method
print(dtobj_hongkong)

回答 3

我想我想通了:计算从纪元以来的秒数,然后使用time.localtime转换为本地timzeone,然后将时间结构转换回datetime …

EPOCH_DATETIME = datetime.datetime(1970,1,1)
SECONDS_PER_DAY = 24*60*60

def utc_to_local_datetime( utc_datetime ):
    delta = utc_datetime - EPOCH_DATETIME
    utc_epoch = SECONDS_PER_DAY * delta.days + delta.seconds
    time_struct = time.localtime( utc_epoch )
    dt_args = time_struct[:6] + (delta.microseconds,)
    return datetime.datetime( *dt_args )

它正确地应用了夏/夏DST:

>>> utc_to_local_datetime( datetime.datetime(2010, 6, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 6, 6, 19, 29, 7, 730000)
>>> utc_to_local_datetime( datetime.datetime(2010, 12, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 12, 6, 18, 29, 7, 730000)

I think I figured it out: computes number of seconds since epoch, then converts to a local timzeone using time.localtime, and then converts the time struct back into a datetime…

EPOCH_DATETIME = datetime.datetime(1970,1,1)
SECONDS_PER_DAY = 24*60*60

def utc_to_local_datetime( utc_datetime ):
    delta = utc_datetime - EPOCH_DATETIME
    utc_epoch = SECONDS_PER_DAY * delta.days + delta.seconds
    time_struct = time.localtime( utc_epoch )
    dt_args = time_struct[:6] + (delta.microseconds,)
    return datetime.datetime( *dt_args )

It applies the summer/winter DST correctly:

>>> utc_to_local_datetime( datetime.datetime(2010, 6, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 6, 6, 19, 29, 7, 730000)
>>> utc_to_local_datetime( datetime.datetime(2010, 12, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 12, 6, 18, 29, 7, 730000)

回答 4

基于Alexei的评论。这也适用于DST。

import time
import datetime

def utc_to_local(dt):
    if time.localtime().tm_isdst:
        return dt - datetime.timedelta(seconds = time.altzone)
    else:
        return dt - datetime.timedelta(seconds = time.timezone)

Building on Alexei’s comment. This should work for DST too.

import time
import datetime

def utc_to_local(dt):
    if time.localtime().tm_isdst:
        return dt - datetime.timedelta(seconds = time.altzone)
    else:
        return dt - datetime.timedelta(seconds = time.timezone)

回答 5

标准的Python库没有附带 tzinfo实现。我一直认为这是datetime模块的一个令人惊讶的缺点。

tzinfo类文档的确提供了一些有用的示例。在本节末尾查找较大的代码块。

The standard Python library does not come with any tzinfo implementations at all. I’ve always considered this a surprising shortcoming of the datetime module.

The documentation for the tzinfo class does come with some useful examples. Look for the large code block at the end of the section.


回答 6

Python 3.9添加了zoneinfo模块,因此现在可以按以下步骤完成(仅stdlib):

from zoneinfo import ZoneInfo
from datetime import datetime

utc_unaware = datetime(2020, 10, 31, 12)  # loaded from database
utc_aware = utc_unaware.replace(tzinfo=ZoneInfo('UTC'))  # make aware
local_aware = utc_aware.astimezone(ZoneInfo('localtime'))  # convert

中欧比UTC提前1或2个小时,因此local_aware

datetime.datetime(2020, 10, 31, 13, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='localtime'))

如下str

2020-10-31 13:00:00+01:00

Windows 没有系统时区数据库,因此这里需要一个额外的程序包:

pip install tzdata  

有一个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 it can be done as follows (stdlib only):

from zoneinfo import ZoneInfo
from datetime import datetime

utc_unaware = datetime(2020, 10, 31, 12)  # loaded from database
utc_aware = utc_unaware.replace(tzinfo=ZoneInfo('UTC'))  # make aware
local_aware = utc_aware.astimezone(ZoneInfo('localtime'))  # convert

Central Europe is 1 or 2 hours ahead of UTC, so local_aware is:

datetime.datetime(2020, 10, 31, 13, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='localtime'))

as str:

2020-10-31 13:00:00+01:00

Windows has no system time zone database, so here an extra package is needed:

pip install tzdata  

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

回答 7

一种适用于Python 2和3的简单(但可能有缺陷)方法:

import time
import datetime

def utc_to_local(dt):
    return dt - datetime.timedelta(seconds = time.timezone)

它的优点是编写一个逆函数很简单

A simple (but maybe flawed) way that works in Python 2 and 3:

import time
import datetime

def utc_to_local(dt):
    return dt - datetime.timedelta(seconds = time.timezone)

Its advantage is that it’s trivial to write an inverse function


回答 8

我发现的最简单的方法是获取所在位置的时间偏移,然后从小时中减去该时间。

def format_time(ts,offset):
    if not ts.hour >= offset:
        ts = ts.replace(day=ts.day-1)
        ts = ts.replace(hour=ts.hour-offset)
    else:
        ts = ts.replace(hour=ts.hour-offset)
    return ts

这对我有用,在Python 3.5.2中。

The easiest way I have found is to get the time offset of where you are, then subtract that from the hour.

def format_time(ts,offset):
    if not ts.hour >= offset:
        ts = ts.replace(day=ts.day-1)
        ts = ts.replace(hour=ts.hour-offset)
    else:
        ts = ts.replace(hour=ts.hour-offset)
    return ts

This works for me, in Python 3.5.2.


回答 9

这是更改日期时间格式的时区的另一种方法(我知道我在此上浪费了精力,但是我没有看到此页面,所以我不知道如何)而没有分钟。和秒。因为我的项目不需要它:

def change_time_zone(year, month, day, hour):
      hour = hour + 7 #<-- difference
      if hour >= 24:
        difference = hour - 24
        hour = difference
        day += 1
        long_months = [1, 3, 5, 7, 8, 10, 12]
        short_months = [4, 6, 9, 11]
        if month in short_months:
          if day >= 30:
            day = 1
            month += 1
            if month > 12:
              year += 1
        elif month in long_months:
          if day >= 31:
            day = 1
            month += 1
            if month > 12:
              year += 1
        elif month == 2:
          if not year%4==0:
            if day >= 29:
              day = 1
              month += 1
              if month > 12:
                year += 1
          else:
            if day >= 28:
              day = 1
              month += 1
              if month > 12:
                year += 1
      return datetime(int(year), int(month), int(day), int(hour), 00)

Here is another way to change timezone in datetime format (I know I wasted my energy on this but I didn’t see this page so I don’t know how) without min. and sec. cause I don’t need it for my project:

def change_time_zone(year, month, day, hour):
      hour = hour + 7 #<-- difference
      if hour >= 24:
        difference = hour - 24
        hour = difference
        day += 1
        long_months = [1, 3, 5, 7, 8, 10, 12]
        short_months = [4, 6, 9, 11]
        if month in short_months:
          if day >= 30:
            day = 1
            month += 1
            if month > 12:
              year += 1
        elif month in long_months:
          if day >= 31:
            day = 1
            month += 1
            if month > 12:
              year += 1
        elif month == 2:
          if not year%4==0:
            if day >= 29:
              day = 1
              month += 1
              if month > 12:
                year += 1
          else:
            if day >= 28:
              day = 1
              month += 1
              if month > 12:
                year += 1
      return datetime(int(year), int(month), int(day), int(hour), 00)

回答 10

这是一种糟糕的方法,但是避免了创建定义。它满足了坚持使用基本Python3库的要求。

# Adjust from UST to Eastern Standard Time (dynamic)
# df.my_localtime should already be in datetime format, so just in case
df['my_localtime'] = pd.to_datetime.df['my_localtime']

df['my_localtime'] = df['my_localtime'].dt.tz_localize('UTC').dt.tz_convert('America/New_York').astype(str)
df['my_localtime'] = pd.to_datetime(df.my_localtime.str[:-6])

This is a terrible way to do it but it avoids creating a definition. It fulfills the requirement to stick with the basic Python3 library.

# Adjust from UST to Eastern Standard Time (dynamic)
# df.my_localtime should already be in datetime format, so just in case
df['my_localtime'] = pd.to_datetime.df['my_localtime']

df['my_localtime'] = df['my_localtime'].dt.tz_localize('UTC').dt.tz_convert('America/New_York').astype(str)
df['my_localtime'] = pd.to_datetime(df.my_localtime.str[:-6])

回答 11

使用timedelta在时区之间切换。您所需要的只是时区之间的小时数偏移。不必摆弄日期时间对象的所有6个元素的边界。timedelta也可以轻松处理leap年,leap历世纪等。你必须先

from datetime import datetime, timedelta

那如果 offset是时区增量(以小时为单位):

timeout = timein + timedelta(hours = offset)

其中timein和timeout是日期时间对象。例如

timein + timedelta(hours = -8)

从GMT转换为PST。

那么,如何确定 offset?这是一个简单的函数,前提是您只有很少的转换可能性而无需使用时区“可感知”的日期时间对象,而其他一些答案很好地做到了这一点。有点手册,但有时清晰度最好。

def change_timezone(timein, timezone, timezone_out):
    '''
    changes timezone between predefined timezone offsets to GMT
    timein - datetime object
    timezone - 'PST', 'PDT', 'GMT' (can add more as needed)
    timezone_out - 'PST', 'PDT', 'GMT' (can add more as needed)
    ''' 
    # simple table lookup        
    tz_offset =  {'PST': {'GMT': 8, 'PDT': 1, 'PST': 0}, \
                  'GMT': {'PST': -8, 'PDT': -7, 'GMT': 0}, \
                  'PDT': {'GMT': 7, 'PST': -1, 'PDT': 0}}
    try:
        offset = tz_offset[timezone][timezone_out]
    except:
        msg = 'Input timezone=' + timezone + ' OR output time zone=' + \
            timezone_out + ' not recognized'
        raise DateTimeError(msg)

    return timein + timedelta(hours = offset)

在查看了无数的答案并尝试了我能想到的最严格的代码之后(目前),似乎所有时间都非常重要且必须考虑混合时区的应用程序似乎应该尽一切努力来制作所有datetime对象“知道的”。那么,最简​​单的答案似乎是:

timeout = timein.astimezone(pytz.timezone("GMT"))

例如转换为格林尼治标准时间。当然,要与您希望的任何其他时区(本地或其他)进行相互转换,只需使用pytz可以理解的适当时区字符串(来自pytz.all_timezones)。然后还要考虑夏令时。

Use timedelta to switch between timezones. All you need is the offset in hours between timezones. Don’t have to fiddle with boundaries for all 6 elements of a datetime object. timedelta handles leap years, leap centuries, etc., too, with ease. You must first

from datetime import datetime, timedelta

Then if offset is the timezone delta in hours:

timeout = timein + timedelta(hours = offset)

where timein and timeout are datetime objects. e.g.

timein + timedelta(hours = -8)

converts from GMT to PST.

So, how to determine offset? Here is a simple function provided you only have a few possibilities for conversion without using datetime objects that are timezone “aware” which some other answers nicely do. A bit manual, but sometimes clarity is best.

def change_timezone(timein, timezone, timezone_out):
    '''
    changes timezone between predefined timezone offsets to GMT
    timein - datetime object
    timezone - 'PST', 'PDT', 'GMT' (can add more as needed)
    timezone_out - 'PST', 'PDT', 'GMT' (can add more as needed)
    ''' 
    # simple table lookup        
    tz_offset =  {'PST': {'GMT': 8, 'PDT': 1, 'PST': 0}, \
                  'GMT': {'PST': -8, 'PDT': -7, 'GMT': 0}, \
                  'PDT': {'GMT': 7, 'PST': -1, 'PDT': 0}}
    try:
        offset = tz_offset[timezone][timezone_out]
    except:
        msg = 'Input timezone=' + timezone + ' OR output time zone=' + \
            timezone_out + ' not recognized'
        raise DateTimeError(msg)

    return timein + timedelta(hours = offset)

After looking at the numerous answers and playing around with the tightest code I can think of (for now) it seems best that all applications, where time is important and mixed timezones must be accounted for, should make a real effort to make all datetime objects “aware”. Then it would seem the simplest answer is:

timeout = timein.astimezone(pytz.timezone("GMT"))

to convert to GMT for example. Of course, to convert to/from any other timezone you wish, local or otherwise, just use the appropriate timezone string that pytz understands (from pytz.all_timezones). Daylight savings time is then also taken into account.


将timedelta转换为总秒数

问题:将timedelta转换为总秒数

我有时间差

time1 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
...
time2 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
diff = time2 - time1

现在,我如何找到经过的总秒数?diff.seconds不算数天。我可以:

diff.seconds + diff.days * 24 * 3600

有内置的方法吗?

I have a time difference

import time
import datetime

time1 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
...
time2 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
diff = time2 - time1

Now, how do I find the total number of seconds that passed? diff.seconds doesn’t count days. I could do:

diff.seconds + diff.days * 24 * 3600

Is there a builtin method for this?


回答 0

使用timedelta.total_seconds()

>>> import datetime
>>> datetime.timedelta(seconds=24*60*60).total_seconds()
86400.0

Use timedelta.total_seconds().

>>> import datetime
>>> datetime.timedelta(seconds=24*60*60).total_seconds()
86400.0

回答 1

您的一个或另一个问题 datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))表达。

(1)如果您所需要的只是两秒之间的差异,那么就很简单time.time()

(2)如果您将这些时间戳记用于其他目的,则需要考虑您在做什么,因为结果在整个过程中都有很大的气味:

gmtime()UTC返回一个时间元组,但是mktime()期望以本地时间为时间元组

我在澳大利亚的墨尔本,标准TZ是UTC + 10,但是夏令时仍然有效,直到明天早上,所以是UTC + 11。当我执行以下命令时,这是当地时间2011-04-02T20:31 … UTC是2011-04-02T09:31

>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time

您会注意到,t3表达式的结果是UTC + 1,这似乎是UTC +(我的本地DST差异)……不是很有意义。您应该考虑使用datetime.datetime.utcnow()DST开启/关闭时不会跳一个小时的方法,它可能会比time.time()

You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) expression.

(1) If all you need is the difference between two instants in seconds, the very simple time.time() does the job.

(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:

gmtime() returns a time tuple in UTC but mktime() expects a time tuple in local time.

I’m in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it’s UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here … UTC was 2011-04-02T09:31

>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time

You’ll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) … not very meaningful. You should consider using datetime.datetime.utcnow() which won’t jump by an hour when DST goes on/off and may give you more precision than time.time()


回答 2

您可以使用mx.DateTime模块

import mx.DateTime as mt

t1 = mt.now() 
t2 = mt.now()
print int((t2-t1).seconds)

You can use mx.DateTime module

import mx.DateTime as mt

t1 = mt.now() 
t2 = mt.now()
print int((t2-t1).seconds)

将datetime转换为Unix时间戳并将其转换回python

问题:将datetime转换为Unix时间戳并将其转换回python

我有dt = datetime(2013,9,1,11),并且我想获取此datetime对象的Unix时间戳。

当我这样做的时候,(dt - datetime(1970,1,1)).total_seconds()我得到了时间戳1378033200

当使用datetime.fromtimestamp我将其转换回时datetime.datetime(2013, 9, 1, 6, 0)

时间不匹配。我在这里想念什么?

I have dt = datetime(2013,9,1,11), and I would like to get a Unix timestamp of this datetime object.

When I do (dt - datetime(1970,1,1)).total_seconds() I got the timestamp 1378033200.

When converting it back using datetime.fromtimestamp I got datetime.datetime(2013, 9, 1, 6, 0).

The hour doesn’t match. What did I miss here?


回答 0

您在这里错过的是时区。

大概您要在UTC下班5个小时,因此2013-09-01T11:00:00本地和2013-09-01T06:00:00Z是同一时间。

您需要阅读datetime文档的顶部,其中解释了时区以及“天真”和“感知”对象。

如果您原始的原始日期时间是UTC,则恢复它的方法是使用utcfromtimestamp而不是fromtimestamp

另一方面,如果原始的原始日期时间是本地的,那么您不应该首先从中减去UTC时间戳;使用datetime.fromtimestamp(0)代替。

或者,如果您有一个已知的日期时间对象,则需要在两侧都使用一个本地(感知)纪元,或者显式地与UTC进行转换。

如果您拥有或可以升级到Python 3.3或更高版本,则可以通过仅使用timestamp方法来避免所有这些问题,而不必尝试自己弄清楚该如何做。即使您不这样做,也可能要考虑借鉴其源代码

(而且,如果您可以等待Python 3.4,则似乎PEP 341可能会进入最终发行版,这意味着JF Sebastian和我在评论中谈论的所有内容都只能使用stdlib来完成,并且在Unix和Windows上均以相同的方式工作。)

What you missed here is timezones.

Presumably you’ve five hours off UTC, so 2013-09-01T11:00:00 local and 2013-09-01T06:00:00Z are the same time.

You need to read the top of the datetime docs, which explain about timezones and “naive” and “aware” objects.

If your original naive datetime was UTC, the way to recover it is to use utcfromtimestamp instead of fromtimestamp.

On the other hand, if your original naive datetime was local, you shouldn’t have subtracted a UTC timestamp from it in the first place; use datetime.fromtimestamp(0) instead.

Or, if you had an aware datetime object, you need to either use a local (aware) epoch on both sides, or explicitly convert to and from UTC.

If you have, or can upgrade to, Python 3.3 or later, you can avoid all of these problems by just using the timestamp method instead of trying to figure out how to do it yourself. And even if you don’t, you may want to consider borrowing its source code.

(And if you can wait for Python 3.4, it looks like PEP 341 is likely to make it into the final release, which means all of the stuff J.F. Sebastian and I were talking about in the comments should be doable with just the stdlib, and working the same way on both Unix and Windows.)


回答 1

解决方案是

import time
import datetime
d = datetime.date(2015,1,5)

unixtime = time.mktime(d.timetuple())

solution is

import time
import datetime
d = datetime.date(2015,1,5)

unixtime = time.mktime(d.timetuple())

回答 2

如果要将python日期时间转换为自纪元以来的秒数,则应明确地执行以下操作:

>>> import datetime
>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0

在Python 3.3+中,您可以timestamp()改用:

>>> import datetime
>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0

If you want to convert a python datetime to seconds since epoch you should do it explicitly:

>>> import datetime
>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0

In Python 3.3+ you can use timestamp() instead:

>>> import datetime
>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0

回答 3

而不是使用此表达式从创建一个POSIX时间戳dt

(dt - datetime(1970,1,1)).total_seconds()

用这个:

int(dt.strftime("%s"))

在使用第二种方法的示例中,我得到了正确的答案。

编辑:一些跟进…经过一些评论(请参阅下文),我很好奇缺少%sin 的支持或文档strftime。这是我发现的:

Python源datetimetime,串STRFTIME_FORMAT_CODES告诉我们:

"Other codes may be available on your platform.
 See documentation for the C library strftime function."

所以现在,如果我们man strftime(在Mac OS X等BSD系统上)可以找到对以下内容的支持%s

"%s is replaced by the number of seconds since the Epoch, UTC (see mktime(3))."

无论如何,这就是为什么%s可以在它可以运行的系统上工作。但是有更好的解决OP问题的方法(考虑了时区)。请参阅此处的@abarnert可接受的答案。

Rather than this expression to create a POSIX timestamp from dt,

(dt - datetime(1970,1,1)).total_seconds()

Use this:

int(dt.strftime("%s"))

I get the right answer in your example using the second method.

EDIT: Some followup… After some comments (see below), I was curious about the lack of support or documentation for %s in strftime. Here’s what I found:

In the Python source for datetime and time, the string STRFTIME_FORMAT_CODES tells us:

"Other codes may be available on your platform.
 See documentation for the C library strftime function."

So now if we man strftime (on BSD systems such as Mac OS X), you’ll find support for %s:

"%s is replaced by the number of seconds since the Epoch, UTC (see mktime(3))."

Anyways, that’s why %s works on the systems it does. But there are better solutions to OP’s problem (that take timezones into account). See @abarnert’s accepted answer here.


回答 4

对于使用UTC时区:

time_stamp = calendar.timegm(dt.timetuple())

datetime.utcfromtimestamp(time_stamp)

For working with UTC timezones:

time_stamp = calendar.timegm(dt.timetuple())

datetime.utcfromtimestamp(time_stamp)

回答 5

您错过了时区信息(已回答,已同意)

arrow包装允许避免约会时间的折磨;它已经被编写,测试,pypi发布,交叉python(2.6 — 3.xx)。

您需要的全部:(pip install arrow或添加到依赖项)

您的情况的解决方案

dt = datetime(2013,9,1,11)
arrow.get(dt).timestamp
# >>> 1378033200

bc = arrow.get(1378033200).datetime
print(bc)
# >>> datetime.datetime(2013, 9, 1, 11, 0, tzinfo=tzutc())
print(bc.isoformat())
# >>> '2013-09-01T11:00:00+00:00'

You’ve missed the time zone info (already answered, agreed)

arrow package allows to avoid this torture with datetimes; It is already written, tested, pypi-published, cross-python (2.6 — 3.xx).

All you need: pip install arrow (or add to dependencies)

Solution for your case

dt = datetime(2013,9,1,11)
arrow.get(dt).timestamp
# >>> 1378033200

bc = arrow.get(1378033200).datetime
print(bc)
# >>> datetime.datetime(2013, 9, 1, 11, 0, tzinfo=tzutc())
print(bc.isoformat())
# >>> '2013-09-01T11:00:00+00:00'

回答 6

如果您的datetime对象表示UTC时间,请不要使用time.mktime,因为它假定元组位于您的本地时区中。而是使用calendar.timegm:

>>> import datetime, calendar
>>> d = datetime.datetime(1970, 1, 1, 0, 1, 0)
>>> calendar.timegm(d.timetuple())
60

If your datetime object represents UTC time, don’t use time.mktime, as it assumes the tuple is in your local timezone. Instead, use calendar.timegm:

>>> import datetime, calendar
>>> d = datetime.datetime(1970, 1, 1, 0, 1, 0)
>>> calendar.timegm(d.timetuple())
60

回答 7

好吧,当转换为unix时间戳时,python基本上采用了UTC,但是当转换回它时,它将给您一个转换为本地时区的日期。

看到这个问题/答案; 从datestamp()获取datetime.datetime.date使用的时区

Well, when converting TO unix timestamp, python is basically assuming UTC, but while converting back it will give you a date converted to your local timezone.

See this question/answer; Get timezone used by datetime.datetime.fromtimestamp()


回答 8

def dt2ts(dt, utc=False):
    if utc:
        return calendar.timegm(dt.timetuple())
    if dt.tzinfo is None:
        return int(time.mktime(dt.timetuple()))
    utc_dt = dt.astimezone(tz.tzutc()).timetuple()
    return calendar.timegm(utc_dt)

如果您想使用UTC时间戳:time.mktime仅用于本地 dt,使用calendar.timegm是安全的,但dt必须是utc区域,因此请将区域更改为utc。如果在UTC中使用dt,请使用calendar.timegm

def dt2ts(dt, utc=False):
    if utc:
        return calendar.timegm(dt.timetuple())
    if dt.tzinfo is None:
        return int(time.mktime(dt.timetuple()))
    utc_dt = dt.astimezone(tz.tzutc()).timetuple()
    return calendar.timegm(utc_dt)

If you want UTC timestamp :time.mktime just for local dt .Use calendar.timegm is safe but dt must the utc zone so change the zone to utc. If dt in UTC just use calendar.timegm.


回答 9

def datetime_to_epoch(d1):

    # create 1,1,1970 in same timezone as d1
    d2 = datetime(1970, 1, 1, tzinfo=d1.tzinfo)
    time_delta = d1 - d2
    ts = int(time_delta.total_seconds())
    return ts


def epoch_to_datetime_string(ts, tz_name="UTC"):
    x_timezone = timezone(tz_name)
    d1 = datetime.fromtimestamp(ts, x_timezone)
    x = d1.strftime("%d %B %Y %H:%M:%S")
    return x
def datetime_to_epoch(d1):

    # create 1,1,1970 in same timezone as d1
    d2 = datetime(1970, 1, 1, tzinfo=d1.tzinfo)
    time_delta = d1 - d2
    ts = int(time_delta.total_seconds())
    return ts


def epoch_to_datetime_string(ts, tz_name="UTC"):
    x_timezone = timezone(tz_name)
    d1 = datetime.fromtimestamp(ts, x_timezone)
    x = d1.strftime("%d %B %Y %H:%M:%S")
    return x

回答 10

该类将满足您的需求,您可以将变量传递给ConvertUnixToDatetime&call,然后基于该变量来运行该函数。

from datetime import datetime
import time

class ConvertUnixToDatetime:
    def __init__(self, date):
        self.date = date

    # Convert unix to date object
    def convert_unix(self):
        unix = self.date

        # Check if unix is a string or int & proceeds with correct conversion
        if type(unix).__name__ == 'str':
            unix = int(unix[0:10])
        else:
            unix = int(str(unix)[0:10])

        date = datetime.utcfromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S')

        return date

    # Convert date to unix object
    def convert_date(self):
        date = self.date

        # Check if datetime object or raise ValueError
        if type(date).__name__ == 'datetime':
            unixtime = int(time.mktime(date.timetuple()))
        else:
            raise ValueError('You are trying to pass a None Datetime object')
        return type(unixtime).__name__, unixtime


if __name__ == '__main__':

    # Test Date
    date_test = ConvertUnixToDatetime(datetime.today())
    date_test = date_test.convert_date()
    print(date_test)

    # Test Unix
    unix_test = ConvertUnixToDatetime(date_test[1])
    print(unix_test.convert_unix())

This class will cover your needs, you can pass the variable into ConvertUnixToDatetime & call which function you want it to operate based off.

from datetime import datetime
import time

class ConvertUnixToDatetime:
    def __init__(self, date):
        self.date = date

    # Convert unix to date object
    def convert_unix(self):
        unix = self.date

        # Check if unix is a string or int & proceeds with correct conversion
        if type(unix).__name__ == 'str':
            unix = int(unix[0:10])
        else:
            unix = int(str(unix)[0:10])

        date = datetime.utcfromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S')

        return date

    # Convert date to unix object
    def convert_date(self):
        date = self.date

        # Check if datetime object or raise ValueError
        if type(date).__name__ == 'datetime':
            unixtime = int(time.mktime(date.timetuple()))
        else:
            raise ValueError('You are trying to pass a None Datetime object')
        return type(unixtime).__name__, unixtime


if __name__ == '__main__':

    # Test Date
    date_test = ConvertUnixToDatetime(datetime.today())
    date_test = date_test.convert_date()
    print(date_test)

    # Test Unix
    unix_test = ConvertUnixToDatetime(date_test[1])
    print(unix_test.convert_unix())

如何在Python中截断DateTime对象上的时间?

问题:如何在Python中截断DateTime对象上的时间?

截断python datetime对象的经典方法是什么?

在这种特殊情况下,直到今天。因此,基本上将小时,分钟,秒和微秒设置为0。

我希望输出也是日期时间对象,而不是字符串。

What is a classy way to way truncate a python datetime object?

In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0.

I would like the output to also be a datetime object, not a string.


回答 0

我认为这就是您要寻找的…

>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy
>>> dt
datetime.datetime(2011, 3, 29, 0, 0)

但是,如果您真的不在乎事物的时间方面,那么您实际上应该只在传递date对象……

>>> d_truncated = datetime.date(dt.year, dt.month, dt.day)
>>> d_truncated
datetime.date(2011, 3, 29)

I think this is what you’re looking for…

>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy
>>> dt
datetime.datetime(2011, 3, 29, 0, 0)

But if you really don’t care about the time aspect of things, then you should really only be passing around date objects…

>>> d_truncated = datetime.date(dt.year, dt.month, dt.day)
>>> d_truncated
datetime.date(2011, 3, 29)

回答 1

如果您不在乎时间,请使用datenot datetime

>>> now = datetime.now()
>>> now.date()
datetime.date(2011, 3, 29)

您可以像这样更新日期时间:

>>> now.replace(minute=0, hour=0, second=0, microsecond=0)
datetime.datetime(2011, 3, 29, 0, 0)

Use a date not a datetime if you dont care about the time.

>>> now = datetime.now()
>>> now.date()
datetime.date(2011, 3, 29)

You can update a datetime like this:

>>> now.replace(minute=0, hour=0, second=0, microsecond=0)
datetime.datetime(2011, 3, 29, 0, 0)

回答 2

四年后:另一种方式,避免 replace

我知道四年前已经接受的答案有效,但是这似乎比使用replace以下要轻:

dt = datetime.date.today()
dt = datetime.datetime(dt.year, dt.month, dt.day)

笔记

  • 当您在datetime不将时间属性传递给构造函数的情况下创建对象时,将出现午夜。
  • 正如其他人所指出的那样,这假设您想要一个datetime对象供以后与timedelta一起使用。
  • 当然,您可以将其替换为第一行: dt = datetime.datetime.now()

Four years later: another way, avoiding replace

I know the accepted answer from four years ago works, but this seems a tad lighter than using replace:

dt = datetime.date.today()
dt = datetime.datetime(dt.year, dt.month, dt.day)

Notes

  • When you create a datetime object without passing time properties to the constructor, you get midnight.
  • As others have noted, this assumes you want a datetime object for later use with timedeltas.
  • You can, of course, substitute this for the first line: dt = datetime.datetime.now()

回答 3

您不能截断日期时间对象,因为它是不可变的

但是,这是一种使用0小时,分钟,秒和微秒字段构造新日期时间而不丢弃原始日期或tzinfo的方法:

newdatetime = now.replace(hour=0, minute=0, second=0, microsecond=0)

You cannot truncate a datetime object because it is immutable.

However, here is one way to construct a new datetime with 0 hour, minute, second, and microsecond fields, without throwing away the original date or tzinfo:

newdatetime = now.replace(hour=0, minute=0, second=0, microsecond=0)

回答 4

要获得对应于给定日期时间对象的午夜,可以使用datetime.combine()method

>>> from datetime import datetime, time
>>> dt = datetime.utcnow()
>>> dt.date()
datetime.date(2015, 2, 3)
>>> datetime.combine(dt, time.min)
datetime.datetime(2015, 2, 3, 0, 0)

.replace()方法相比,优点是datetime.combine()即使datetime模块引入了纳秒级支持,基于解决方案的解决方案仍将继续有效。

tzinfo可以在必要时保留它,但是utc偏移量可能在午夜有所不同,例如由于DST转换,因此幼稚的解决方案(设置tzinfo时间属性)可能会失败。请参阅如何获取给定时区的UTC时间“午夜”?

To get a midnight corresponding to a given datetime object, you could use datetime.combine() method:

>>> from datetime import datetime, time
>>> dt = datetime.utcnow()
>>> dt.date()
datetime.date(2015, 2, 3)
>>> datetime.combine(dt, time.min)
datetime.datetime(2015, 2, 3, 0, 0)

The advantage compared to the .replace() method is that datetime.combine()-based solution will continue to work even if datetime module introduces the nanoseconds support.

tzinfo can be preserved if necessary but the utc offset may be different at midnight e.g., due to a DST transition and therefore a naive solution (setting tzinfo time attribute) may fail. See How do I get the UTC time of “midnight” for a given timezone?


回答 5

您可以为此使用熊猫(尽管对于该任务可能是开销)。您可以像通常的数字一样使用roundfloorceil,也可以使用offset-aliases的任何熊猫频率:

import pandas as pd
import datetime as dt

now = dt.datetime.now()
pd_now = pd.Timestamp(now)

freq = '1d'
pd_round = pd_now.round(freq)
dt_round = pd_round.to_pydatetime()

print(now)
print(dt_round)

"""
2018-06-15 09:33:44.102292
2018-06-15 00:00:00
"""

You could use pandas for that (although it could be overhead for that task). You could use round, floor and ceil like for usual numbers and any pandas frequency from offset-aliases:

import pandas as pd
import datetime as dt

now = dt.datetime.now()
pd_now = pd.Timestamp(now)

freq = '1d'
pd_round = pd_now.round(freq)
dt_round = pd_round.to_pydatetime()

print(now)
print(dt_round)

"""
2018-06-15 09:33:44.102292
2018-06-15 00:00:00
"""

回答 6

您可以使用datetime.strftime提取日期,月份,年份…

范例:

from datetime import datetime
d = datetime.today()

# Retrieves the day and the year
print d.strftime("%d-%Y")

输出(今天):

29-2011

如果只想获取日期,则可以使用day属性,例如:

from datetime import datetime
d = datetime.today()

# Retrieves the day
print d.day

Ouput(今天):

29

You can use datetime.strftime to extract the day, the month, the year…

Example :

from datetime import datetime
d = datetime.today()

# Retrieves the day and the year
print d.strftime("%d-%Y")

Output (for today):

29-2011

If you just want to retrieve the day, you can use day attribute like :

from datetime import datetime
d = datetime.today()

# Retrieves the day
print d.day

Ouput (for today):

29

回答 7

有一个很棒的用于操作日期的库:Delorean

import datetime
from delorean import Delorean
now = datetime.datetime.now()
d = Delorean(now, timezone='US/Pacific')

>>> now    
datetime.datetime(2015, 3, 26, 19, 46, 40, 525703)

>>> d.truncate('second')
Delorean(datetime=2015-03-26 19:46:40-07:00, timezone='US/Pacific')

>>> d.truncate('minute')
Delorean(datetime=2015-03-26 19:46:00-07:00, timezone='US/Pacific')

>>> d.truncate('hour')
Delorean(datetime=2015-03-26 19:00:00-07:00, timezone='US/Pacific')

>>> d.truncate('day')
Delorean(datetime=2015-03-26 00:00:00-07:00, timezone='US/Pacific')

>>> d.truncate('month')
Delorean(datetime=2015-03-01 00:00:00-07:00, timezone='US/Pacific')

>>> d.truncate('year')
Delorean(datetime=2015-01-01 00:00:00-07:00, timezone='US/Pacific')

并且如果您想获取日期时间值:

>>> d.truncate('year').datetime
datetime.datetime(2015, 1, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)

There is a great library used to manipulate dates: Delorean

import datetime
from delorean import Delorean
now = datetime.datetime.now()
d = Delorean(now, timezone='US/Pacific')

>>> now    
datetime.datetime(2015, 3, 26, 19, 46, 40, 525703)

>>> d.truncate('second')
Delorean(datetime=2015-03-26 19:46:40-07:00, timezone='US/Pacific')

>>> d.truncate('minute')
Delorean(datetime=2015-03-26 19:46:00-07:00, timezone='US/Pacific')

>>> d.truncate('hour')
Delorean(datetime=2015-03-26 19:00:00-07:00, timezone='US/Pacific')

>>> d.truncate('day')
Delorean(datetime=2015-03-26 00:00:00-07:00, timezone='US/Pacific')

>>> d.truncate('month')
Delorean(datetime=2015-03-01 00:00:00-07:00, timezone='US/Pacific')

>>> d.truncate('year')
Delorean(datetime=2015-01-01 00:00:00-07:00, timezone='US/Pacific')

and if you want to get datetime value back:

>>> d.truncate('year').datetime
datetime.datetime(2015, 1, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)

回答 8

参见https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html

现在是2019年,我认为最有效的方法是:

df['truncate_date'] = df['timestamp'].dt.floor('d')

See more at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html

It’s now 2019, I think the most efficient way to do it is:

df['truncate_date'] = df['timestamp'].dt.floor('d')

回答 9

有一个模块datetime_truncate可以为您处理。它只是调用datetime.replace。

There is a module datetime_truncate which handlers this for you. It just calls datetime.replace.


回答 10

6年后…我发现了这篇文章,并且我更喜欢numpy的方式:

import numpy as np
dates_array = np.array(['2013-01-01', '2013-01-15', '2013-01-30']).astype('datetime64[ns]')
truncated_dates = dates_array.astype('datetime64[D]')

干杯

6 years later… I found this post and I liked more the numpy aproach:

import numpy as np
dates_array = np.array(['2013-01-01', '2013-01-15', '2013-01-30']).astype('datetime64[ns]')
truncated_dates = dates_array.astype('datetime64[D]')

cheers


回答 11

>>> import datetime
>>> dt = datetime.datetime.now()
>>> datetime.datetime.date(dt)
datetime.date(2019, 4, 2)
>>> import datetime
>>> dt = datetime.datetime.now()
>>> datetime.datetime.date(dt)
datetime.date(2019, 4, 2)

回答 12

你可以用

datetime.date.today()

轻巧,可精确返回您想要的东西。

You can just use

datetime.date.today()

It’s light and returns exactly what you want.


回答 13

截断是什么意思?

通过使用strftime()方法并使用适当的格式字符串,您可以完全控制格式。

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

What does truncate mean?

You have full control over the formatting by using the strftime() method and using an appropriate format string.

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


回答 14

如果要处理DateTime类型的Series,则有一种更有效的方法来截断它们,尤其是在Series对象包含很多行时。

您可以使用发言权功能

例如,如果要将其截断为几个小时:

产生日期范围

times = pd.Series(pd.date_range(start='1/1/2018 04:00:00', end='1/1/2018 22:00:00', freq='s'))

我们可以通过比较替换功能和发言权功能之间的运行时间来检查它。

%timeit times.apply(lambda x : x.replace(minute=0, second=0, microsecond=0))
>>> 341 ms ± 18.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit times.dt.floor('h')
>>>>2.26 ms ± 451 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

If you are dealing with a Series of type DateTime there is a more efficient way to truncate them, specially when the Series object has a lot of rows.

You can use the floor function

For example, if you want to truncate it to hours:

Generate a range of dates

times = pd.Series(pd.date_range(start='1/1/2018 04:00:00', end='1/1/2018 22:00:00', freq='s'))

We can check it comparing the running time between the replace and the floor functions.

%timeit times.apply(lambda x : x.replace(minute=0, second=0, microsecond=0))
>>> 341 ms ± 18.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit times.dt.floor('h')
>>>>2.26 ms ± 451 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

回答 15

这是适合另一行但又不是特别优雅的另一种方式:

dt = datetime.datetime.fromordinal(datetime.date.today().toordinal())

Here is yet another way which fits in one line but is not particularly elegant:

dt = datetime.datetime.fromordinal(datetime.date.today().toordinal())

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

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

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

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

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

The time module can be initialized using seconds since epoch:

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

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


回答 0

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

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

要么

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

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

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

or

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

回答 1

纪元以来的秒数来datetimestrftime

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

Seconds since epoch to datetime to strftime:

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

回答 2

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

Python 3

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

Python 2,使用pytz

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

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

Python 3:

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

Python 2, using pytz:

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

回答 3

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

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

另请参见Issue1646728

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

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

See also Issue1646728


将Pandas列转换为DateTime

问题:将Pandas列转换为DateTime

我在以字符串格式导入的pandas DataFrame中有一个字段。它应该是日期时间变量。如何将其转换为datetime列,然后根据日期进行过滤。

例:

  • 数据框名称:raw_data
  • 列名称:Mycol
  • 列中的值格式:“ 05SEP2014:00:00:00.000”

I have one field in a pandas DataFrame that was imported as string format. It should be a datetime variable. How do I convert it to a datetime column and then filter based on date.

Example:

  • DataFrame Name: raw_data
  • Column Name: Mycol
  • Value Format in Column: ’05SEP2014:00:00:00.000′

回答 0

使用该to_datetime函数,指定一种格式以匹配您的数据。

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

Use the to_datetime function, specifying a format to match your data.

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

回答 1

您可以使用DataFrame方法.apply()对Mycol中的值进行操作:

>>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
>>> df
                    Mycol
0  05SEP2014:00:00:00.000
>>> import datetime as dt
>>> df['Mycol'] = df['Mycol'].apply(lambda x: 
                                    dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
>>> df
       Mycol
0 2014-09-05

You can use the DataFrame method .apply() to operate on the values in Mycol:

>>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
>>> df
                    Mycol
0  05SEP2014:00:00:00.000
>>> import datetime as dt
>>> df['Mycol'] = df['Mycol'].apply(lambda x: 
                                    dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
>>> df
       Mycol
0 2014-09-05

回答 2

如果要转换的列不止一个,则可以执行以下操作:

df[["col1", "col2", "col3"]] = df[["col1", "col2", "col3"]].apply(pd.to_datetime)

If you have more than one column to be converted you can do the following:

df[["col1", "col2", "col3"]] = df[["col1", "col2", "col3"]].apply(pd.to_datetime)

回答 3

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

可以,但是会导致Python警告:试图在DataFrame的切片副本上设置一个值。尝试.loc[row_indexer,col_indexer] = value改用

我猜这是由于一些链接索引。

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

works, however it results in a Python warning of A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

I would guess this is due to some chaining indexing.


回答 4

使用pandas to_datetime函数将列解析为DateTime。另外,通过使用infer_datetime_format=True,它将自动检测格式并将提到的列转换为DateTime。

import pandas as pd
raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], infer_datetime_format=True)

Use the pandas to_datetime function to parse the column as DateTime. Also, by using infer_datetime_format=True, it will automatically detect the format and convert the mentioned column to DateTime.

import pandas as pd
raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], infer_datetime_format=True)

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

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

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

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

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

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

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

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


回答 0

datetime.timedelta()

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

Use datetime.timedelta()

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

回答 1

from datetime import datetime, timedelta

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

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

回答 2

这应该做您想要的:

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

This should do what you want:

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

回答 3

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

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

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

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

回答 4

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

from datetime import datetime, timedelta

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

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

from datetime import datetime, timedelta

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

回答 5

扩展克里斯给出的答案

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

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

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

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

To expand on the answer given by Chris

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

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

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

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