标签归档:datetime-format

将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日期时间到没有微秒组件的字符串

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

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

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

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

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

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

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

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

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

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

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


回答 0

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

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

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

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

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

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


回答 1

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

回答 2

在Python 3.6中:

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

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

In Python 3.6:

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

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


回答 3

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

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

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

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

This is the way I do it. ISO format:

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

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

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

回答 4

另一个选择:

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

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

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

Yet another option:

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

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

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

回答 5

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

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

Keep the first 19 characters that you wanted via slicing:

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

回答 6

我通常这样做:

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

# To print now:
print(now)

输出:

2019-01-13 14:40:28

I usually do:

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

# To print now:
print(now)

output:

2019-01-13 14:40:28

回答 7

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

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

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

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

回答 8

我们可以尝试如下

import datetime

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

We can try something like below

import datetime

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

回答 9

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

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

I found this to be the simplest way.

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

回答 10

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

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

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

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