标签归档:python-datetime

仅使用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.


将DataFrame列类型从字符串转换为日期时间,格式为dd / mm / yyyy

问题:将DataFrame列类型从字符串转换为日期时间,格式为dd / mm / yyyy

如何将字符串的DataFrame列(以dd / mm / yyyy格式)转换为日期时间?

How can I convert a DataFrame column of strings (in dd/mm/yyyy format) to datetimes?


回答 0

最简单的方法是使用to_datetime

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

它还dayfirst为欧洲时代提供了依据(但请注意,这并不严格)。

它在起作用:

In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0   2005-05-23 00:00:00
dtype: datetime64[ns]

您可以传递特定格式

In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0   2005-05-23
dtype: datetime64[ns]

The easiest way is to use to_datetime:

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

It also offers a dayfirst argument for European times (but beware this isn’t strict).

Here it is in action:

In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0   2005-05-23 00:00:00
dtype: datetime64[ns]

You can pass a specific format:

In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0   2005-05-23
dtype: datetime64[ns]

回答 1

如果您的日期列是格式为’2017-01-01’的字符串,则可以使用pandas astype将其转换为日期时间。

df['date'] = df['date'].astype('datetime64[ns]')

或使用datetime64 [D](如果您想要“天”精度而不是纳秒)

print(type(df_launath['date'].iloc[0]))

Yield

<class 'pandas._libs.tslib.Timestamp'> 与使用pandas.to_datetime时相同

您可以尝试使用其他格式,然后是’%Y-%m-%d’,但至少可以使用。

If your date column is a string of the format ‘2017-01-01’ you can use pandas astype to convert it to datetime.

df['date'] = df['date'].astype('datetime64[ns]')

or use datetime64[D] if you want Day precision and not nanoseconds

print(type(df_launath['date'].iloc[0]))

yields

<class 'pandas._libs.tslib.Timestamp'> the same as when you use pandas.to_datetime

You can try it with other formats then ‘%Y-%m-%d’ but at least this works.


回答 2

如果要指定复杂的格式,可以使用以下内容:

df['date_col'] =  pd.to_datetime(df['date_col'], format='%d/%m/%Y')

format此处的更多详细信息:

You can use the following if you want to specify tricky formats:

df['date_col'] =  pd.to_datetime(df['date_col'], format='%d/%m/%Y')

More details on format here:


回答 3

如果您的约会中有多种格式,别忘了设定infer_datetime_format=True以简化生活

df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)

资料来源:pd.to_datetime

或者,如果您想要定制的方法:

def autoconvert_datetime(value):
    formats = ['%m/%d/%Y', '%m-%d-%y']  # formats to try
    result_format = '%d-%m-%Y'  # output format
    for dt_format in formats:
        try:
            dt_obj = datetime.strptime(value, dt_format)
            return dt_obj.strftime(result_format)
        except Exception as e:  # throws exception when format doesn't match
            pass
    return value  # let it be if it doesn't match

df['date'] = df['date'].apply(autoconvert_datetime)

If you have a mixture of formats in your date, don’t forget to set infer_datetime_format=True to make life easier

df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)

Source: pd.to_datetime

or if you want a customized approach:

def autoconvert_datetime(value):
    formats = ['%m/%d/%Y', '%m-%d-%y']  # formats to try
    result_format = '%d-%m-%Y'  # output format
    for dt_format in formats:
        try:
            dt_obj = datetime.strptime(value, dt_format)
            return dt_obj.strftime(result_format)
        except Exception as e:  # throws exception when format doesn't match
            pass
    return value  # let it be if it doesn't match

df['date'] = df['date'].apply(autoconvert_datetime)

在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')