在python中将numpy.datetime64转换为字符串对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19502506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:54:19  来源:igfitidea点击:

Convert numpy.datetime64 to string object in python

pythondatedatetimenumpy

提问by cs_newbie

I am having trouble converting a python datetime64object into a string. For example:

我在将 pythondatetime64对象转换为字符串时遇到问题。例如:

t = numpy.datetime64('2012-06-30T20:00:00.000000000-0400')

Into:

进入:

'2012.07.01' as a  string. (note time difference)

I have already tried to convert the datetime64object to a datetimelong then to a string, but I seem to get this error:

我已经尝试将datetime64对象转换为datetimelong 然后转换为字符串,但我似乎收到此错误:

dt = t.astype(datetime.datetime) #1341100800000000000L
time.ctime(dt)
ValueError: unconvertible time

回答by cs_newbie

Solution was:

解决方案是:

import pandas as pd 
ts = pd.to_datetime(str(date)) 
d = ts.strftime('%Y.%m.%d')

回答by Wirawan Purwanto

There is a route without using pandas; but see caveat below.

有一条不使用pandas的路由;但请参阅下面的警告。

Well, the tvariable has a resolution of nanoseconds, which can be shown by inspection in python:

好吧,该t变量的分辨率为纳秒,可以通过在 python 中检查来显示:

>>> numpy.dtype(t)
dtype('<M8[ns]')

This means that the integral value of this value is 10^9 times the UNIX timestamp. The value printed in your question gives that hint. Your best bet is to divide the integral value of tby 1 billion then you can use time.strftime:

这意味着该值的整数值是 UNIX 时间戳的 10^9 倍。您的问题中打印的值给出了提示。最好的办法是将 的积分值t除以 10 亿,然后您可以使用time.strftime

>>> import time
>>> time.strftime("%Y.%m.%d", time.gmtime(t.astype(int)/1000000000))
2012.07.01

In using this, be conscious of two assumptions:

在使用它时,请注意两个假设:

1) the datetime64 resolution is nanosecond

1) datetime64 分辨率为纳秒

2) the time stored in datetime64 is in UTC

2) datetime64 中存储的时间是UTC

Side note 1: Interestingly, the numpy developers decided [1] that datetime64object that has a resolution greater than microsecond will be cast to a longtype, which explains why t.astype(datetime.datetime)yields 1341100800000000000L. The reason is that datetime.datetimeobject can't accurately represent a nanosecond or finer timescale, because the resolution supported by datetime.datetimeis only microsecond.

旁注 1:有趣的是,numpy 开发人员决定 [1]datetime64分辨率大于微秒的对象将被强制转换为long类型,这解释了为什么t.astype(datetime.datetime)yield 1341100800000000000L。原因是datetime.datetime对象不能准确表示纳秒或更精细的时间尺度,因为其支持的分辨率datetime.datetime只有微秒。

Side note 2: Beware the different conventions between numpy 1.10 and earlier vs 1.11 and later:

旁注 2:注意 numpy 1.10 及更早版本与 1.11 及更高版本之间的不同约定:

  • in numpy <= 1.10, datetime64 is stored internally as UTC, and printed as local time. Parsing is assuming local time if no TZ is specified, otherwise the timezone offset is accounted for.

  • in numpy >= 1.11, datetime64 is stored internally as timezone-agnostic value (seconds since 1970-01-01 00:00 in unspecified timezone), and printed as such. Time parsing does not assume the timezone, although +NNNNstyle timezone shift is still permitted and that the value is converted to UTC.

  • 在 numpy <= 1.10 中,datetime64 在内部存储为 UTC,并打印为本地时间。如果未指定 TZ,则解析假定本地时间,否则会考虑时区偏移。

  • 在 numpy >= 1.11 中,datetime64 在内部存储为与时区无关的值(未指定时区中自 1970-01-01 00:00 以来的秒数),并按原样打印。时间解析不假定时区,尽管+NNNN仍然允许样式时区转换并且该值转换为 UTC。

[1]: https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/datetime.csee routine convert_datetime_to_pyobject.

[1]:https: //github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/datetime.c见例程convert_datetime_to_pyobject

回答by citynorman

If you don't want to do that conversion gobbledygook and are ok with just one date format, this was the best solution for me

如果您不想进行这种转换 gobbledygook 并且只使用一种日期格式就可以了,那么这对我来说是最好的解决方案

str(t)[:10]
Out[11]: '2012-07-01'

As noted this works for pandas too

如前所述,这也适用于熊猫

df['d'].astype(str).str[:10]
df['d'].dt.strftime('%Y-%m-%d') # equivalent

回答by four43

I wanted an ISO 8601 formatted string without needing any extra dependencies. My numpy_array has a single element as a datetime64. With help from @Wirawan-Purwanto, I added just a bit:

我想要一个 ISO 8601 格式的字符串,而不需要任何额外的依赖项。我的 numpy_array 有一个作为 datetime64 的元素。在@Wirawan-Purwanto 的帮助下,我补充了一点:

from datetime import datetime   

ts = numpy_array.values.astype(datetime)/1000000000
return datetime.utcfromtimestamp(ts).isoformat() # "2018-05-24T19:54:48"

回答by Julie

You can use Numpy's datetime_as_stringfunction. The unit='D'argument specifies the precision, in this case days.

您可以使用 Numpy 的datetime_as_string功能。该unit='D'参数指定的精度,在这种情况下天。

 >>> t = numpy.datetime64('2012-06-30T20:00:00.000000000-0400')
 >>> numpy.datetime_as_string(t, unit='D')
'2012-07-01'

回答by tommy.carstensen

Building on this answerI would do the following:

基于此答案,我将执行以下操作:

import numpy
import datetime
t = numpy.datetime64('2012-06-30T20:00:00.000000000')
datetime.datetime.fromtimestamp(t.item() / 10**9).strftime('%Y.%m.%d')

The division by a billion is to convert from nanoseconds to seconds.

除以十亿是将纳秒转换为秒。