python unix时间戳格式化输出_python - 将unix时间戳字符串转换为可读的d

python - 将unix时间戳字符串转换为可读的d

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

>>>import time

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

Traceback (most recent call last):

File "", line 1, in

TypeError: argument must be 9-item sequence, not str

15个解决方案

932 votes

使用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'))

Michał Niklas answered 2018-12-28T21:24:18Z

190 votes

>>> from datetime import datetime

>>> datetime.fromtimestamp(1172969203.1)

datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

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

Daniel answered 2018-12-28T21:24:40Z

130 votes

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

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

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

rkachach answered 2018-12-28T21:25:09Z

67 votes

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

John La Rooy answered 2018-12-28T21:25:24Z

46 votes

有两个部分:

将unix时间戳(“自纪元以来的秒数”)转换为本地时间

以所需格式显示本地时间。

即使本地时区过去有不同的utc偏移并且python无法访问tz数据库,也可以通过便携方式获取本地时间,这是使用time时区:

#!/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))

jfs answered 2018-12-28T21:26:44Z

32 votes

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

import os, datetime

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

输出:

'2012年12月26日'

Jared Burrows answered 2018-12-28T21:27:16Z

22 votes

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

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

Nick answered 2018-12-28T21:27:46Z

13 votes

除了使用time / datetime包之外,pandas还可以用来解决同样的问题。这就是我们如何使用pandas将时间戳转换为可读日期:

时间戳可以采用两种格式:

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

import pandas

result_s=pandas.to_datetime('1493530261',unit='s')

str(result_s)

Output: '2017-04-30 05:31:01'

10位数(秒) - 要将秒转换为日期,请使用:

import pandas

result_s=pandas.to_datetime('1493530261',unit='s')

str(result_s)

Output: '2017-04-30 05:31:01'

shubham answered 2018-12-28T21:28:55Z

3 votes

import datetime

temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')

print temp

itsaruns answered 2018-12-28T21:29:11Z

3 votes

timestamp ="124542124"

value = datetime.datetime.fromtimestamp(timestamp)

exct_time = value.strftime('%d %B %Y %H:%M:%S')

从时间戳开始随时间获取可读日期,您也可以更改日期格式。

Rishabh Jhalani answered 2018-12-28T21:29:34Z

2 votes

我刚成功使用:

>>> type(tstamp)

pandas.tslib.Timestamp

>>> newDt = tstamp.date()

>>> type(newDt)

datetime.date

nimmy answered 2018-12-28T21:29:56Z

0 votes

快速和脏的一个班轮:

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

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

eqzx answered 2018-12-28T21:30:28Z

-1 votes

您可以使用easy_date轻松完成:

import date_converter

my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")

Raphael Amoedo answered 2018-12-28T21:30:50Z

-2 votes

有一种有趣的方式,您不必担心时区,utc等。只需将字符串转换为Excel日期格式,然后转换为可读的日期/时间:

import datetime

def xldate_to_datetime(xldate):

temp = datetime.datetime(1899, 12, 30)

delta = datetime.timedelta(days=xldate)

return temp+delta

ts = "1284101485"

tsxl = ((int(ts)/60)/60)/24 + 25569

readabledate = xldate_to_datetime(tsxl)

print(readabledate)

Gursel Karacor answered 2018-12-28T21:31:12Z

-12 votes

你看过datetime包吗? 我相信它有一个fromUnixTimestamp方法。

extraneon answered 2018-12-28T21:31:34Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值