1023

我在 Python 中有一个表示 unix 时间戳(即“1284101485”)的字符串,我想将其转换为可读日期。当我使用time.strftime时,我得到一个TypeError

>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str
4

18 回答 18

1430

使用datetime模块:

from datetime import datetime
ts = int('1284101485')

# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
于 2010-09-10T07:09:25.497 回答
302
>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

取自http://seehuhn.de/pages/pdate

于 2010-09-10T06:59:57.103 回答
188

投票最多的答案建议使用 fromtimestamp ,因为它使用本地时区,因此很容易出错。为避免出现问题,更好的方法是使用 UTC:

datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')

其中 posix_time 是您要转换的 Posix 纪元时间

于 2016-05-12T13:23:00.240 回答
88
>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'
于 2010-09-10T08:28:06.940 回答
83

有两个部分:

  1. 将 unix 时间戳(“自纪元以来的秒数”)转换为本地时间
  2. 以所需格式显示本地时间。

即使本地时区过去有不同的 utc 偏移量并且 python 无法访问 tz 数据库,获取本地时间的可移植方法是使用pytz时区:

#!/usr/bin/env python
from datetime import datetime
import tzlocal  # $ pip install tzlocal

unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)

要显示它,您可以使用系统支持的任何时间格式,例如:

print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y"))  # print date in your format

如果您不需要本地时间,请改为获取可读的 UTC 时间:

utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))

如果您不关心可能影响返回日期的时区问题,或者 python 是否可以访问系统上的 tz 数据库:

local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))

在 Python 3 上,您可以仅使用 stdlib 获得时区感知日期时间(如果 python 无法访问系统上的 tz 数据库,例如在 Windows 上,则 UTC 偏移量可能是错误的):

#!/usr/bin/env python3
from datetime import datetime, timezone

utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))

模块中的函数time是围绕相应 C API 的瘦包装器,因此它们的可移植性可能不如相应的datetime方法,否则您也可以使用它们:

#!/usr/bin/env python
import time

unix_timestamp  = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time)) 
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))  
于 2016-11-23T16:30:25.693 回答
62

在 Python 3.6+ 中:

import datetime

timestamp = 1642445213
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")

输出(当地时间)

2022-01-17 20:46:53

解释

奖金

要将日期保存为字符串然后打印它,请使用以下命令:

my_date = f"{value:%Y-%m-%d %H:%M:%S}"
print(my_date)

以 UTC 输出:

value = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
# 2022-01-17 18:50:52
于 2020-01-15T19:52:47.063 回答
40

除了使用time/datetime包,pandas也可以用来解决同样的问题。下面是我们如何使用pandas时间戳转换为可读日期

时间戳可以有两种格式:

  1. 13 位(毫秒) - 要将毫秒转换为日期,请使用:

    import pandas
    result_ms=pandas.to_datetime('1493530261000',unit='ms')
    str(result_ms)
    
    Output: '2017-04-30 05:31:01'
    
  2. 10 位(秒) - 要将转换为日期,请使用:

    import pandas
    result_s=pandas.to_datetime('1493530261',unit='s')
    str(result_s)
    
    Output: '2017-04-30 05:31:01'
    
于 2018-03-07T13:14:32.747 回答
37

对于 UNIX 时间戳中的人类可读时间戳,我之前在脚本中使用过:

import os, datetime

datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")

输出:

'2012 年 12 月 26 日'

于 2012-12-27T02:11:00.393 回答
27

您可以像这样转换当前时间

t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'

将字符串中的日期转换为不同的格式。

import datetime,time

def createDateObject(str_date,strFormat="%Y-%m-%d"):    
    timeStamp = time.mktime(time.strptime(str_date,strFormat))
    return datetime.datetime.fromtimestamp(timeStamp)

def FormatDate(objectDate,strFormat="%Y-%m-%d"):
    return objectDate.strftime(strFormat)

Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')

Output 03-03-2013
于 2012-03-07T07:30:39.950 回答
23
timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')

还可以从时间戳中获取可读的日期,也可以更改日期的格式。

于 2018-08-16T08:56:33.053 回答
12

请注意,这utcfromtimestamp可能会导致意外结果,因为它返回一个简单的日期时间对象。Python 将原始日期时间视为本地时间- 而 UNIX 时间指的是 UTC。

tz可以通过在 中设置参数来避免这种歧义fromtimestamp

from datetime import datetime, timezone

dtobj = datetime.fromtimestamp(1284101485, timezone.utc)

>>> print(repr(dtobj))
datetime.datetime(2010, 9, 10, 6, 51, 25, tzinfo=datetime.timezone.utc)

现在您可以格式化为字符串,例如符合 ISO8601 的格式:

>>> print(dtobj.isoformat(timespec='milliseconds').replace('+00:00', 'Z'))
2010-09-10T06:51:25.000Z
于 2020-11-30T15:47:06.170 回答
9

使用以下代码,希望它能解决您的问题。

import datetime as dt

print(dt.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S'))
于 2021-05-09T16:27:11.877 回答
6
import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp
于 2014-02-05T13:29:07.183 回答
6

可以使用 gmtime 和 format 函数完成此操作的另一种方法;

from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))

输出:2018-10-4 11:57:44

于 2019-01-21T15:18:13.017 回答
3

如果您正在使用数据框并且希望出现series cannot be converted to class int错误。使用下面的代码。

new_df= pd.to_datetime(df_new['time'], unit='s')
于 2021-08-02T05:20:59.037 回答
1

我刚刚成功使用:

>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date
于 2015-01-16T00:44:17.420 回答
1

您可以使用easy_date来简化:

import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")
于 2015-05-15T06:21:59.143 回答
0

快速而肮脏的一个衬垫:

'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))

'2013-5-5-1-9-43'

于 2013-05-05T05:10:00.427 回答