将unix时间戳字符串转换为可读日期

发布于 2024-09-18 04:27:53 字数 411 浏览 10 评论 0原文

我有一个在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

I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use time.strftime, I get a 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

只等公子 2024-09-25 04:27:53

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

Use datetime module:

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'))
坐在坟头思考人生 2024-09-25 04:27:53
>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

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

>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

Taken from http://seehuhn.de/pages/pdate

苯莒 2024-09-25 04:27:53

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

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

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

The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC:

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

Where posix_time is the Posix epoch time you want to convert

我三岁 2024-09-25 04:27:53

有两个部分:

  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 数据库,则 UTC 偏移量可能是错误的在您的系统上(例如,在 Windows 上):

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

There are two parts:

  1. Convert the unix timestamp ("seconds since epoch") to the local time
  2. Display the local time in the desired format.

A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a pytz timezone:

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

To display it, you could use any time format that is supported by your system e.g.:

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

If you do not need a local time, to get a readable UTC time instead:

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

If you don't care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system:

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

On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows):

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

Functions from the time module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding datetime methods otherwise you could use them too:

#!/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))  
叹梦 2024-09-25 04:27:53
>>> 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'
>>> 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'
待天淡蓝洁白时 2024-09-25 04:27:53

在 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

解释

Bonus

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

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

In Python 3.6+:

import datetime

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

Output (local time)

2022-01-17 20:46:53

Explanation

Bonus

To save the date to a string then print it, use this:

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

To output in UTC:

value = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
# 2022-01-17 18:50:52
小嗷兮 2024-09-25 04:27:53

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

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

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

    导入pandas
    result_ms=pandas.to_datetime('1493530261000',unit='ms')
    str(结果_毫秒)
    
    输出:'2017-04-30 05:31:01'
    
  2. 10 位数字(秒)-
    要将转换为日期,请使用:

    导入pandas
    result_s=pandas.to_datetime('1493530261',unit='s')
    str(结果_s)
    
    输出:'2017-04-30 05:31:01'
    

Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:

Timestamps can be in two formats:

  1. 13 digits(milliseconds) -
    To convert milliseconds to date, use:

    import pandas
    result_ms=pandas.to_datetime('1493530261000',unit='ms')
    str(result_ms)
    
    Output: '2017-04-30 05:31:01'
    
  2. 10 digits(seconds) -
    To convert seconds to date, use:

    import pandas
    result_s=pandas.to_datetime('1493530261',unit='s')
    str(result_s)
    
    Output: '2017-04-30 05:31:01'
    
失而复得 2024-09-25 04:27:53

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

import os, datetime

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

输出:

“2012 年 12 月 26 日”

For a human readable timestamp from a UNIX timestamp, I have used this in scripts before:

import os, datetime

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

Output:

'December 26, 2012'

百思不得你姐 2024-09-25 04:27:53

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

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

You can convert the current time like this

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

To convert a date in string to different formats.

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
剑心龙吟 2024-09-25 04:27:53
timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')

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

timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')

Get the readable date from timestamp with time also, also you can change the format of the date.

绅士风度i 2024-09-25 04:27:53

使用 datetime.strftime(format)< /a>:

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

# Print with local time
print(datetime.fromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))

# Print with UTC time
print(datetime.utcfromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))

Use datetime.strftime(format):

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

# Print with local time
print(datetime.fromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))

# Print with UTC time
print(datetime.utcfromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))
可爱咩 2024-09-25 04:27:53

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

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

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

Note that utcfromtimestamp can lead to unexpected results since it returns a naive datetime object. Python treats naive datetime as local time - while UNIX time refers to UTC.

This ambiguity can be avoided by setting the tz argument in 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)

Now you can format to string, e.g. an ISO8601 compliant format:

>>> print(dtobj.isoformat(timespec='milliseconds').replace('+00:00', 'Z'))
2010-09-10T06:51:25.000Z
丶视觉 2024-09-25 04:27:53

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

import datetime as dt

print(dt.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S'))

Use the following codes, I hope it will solve your problem.

import datetime as dt

print(dt.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S'))
浊酒尽余欢 2024-09-25 04:27:53
import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp
import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp
吝吻 2024-09-25 04:27:53

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

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

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

Another way that this can be done using gmtime and format function;

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

Output: 2018-10-4 11:57:44

蓝咒 2024-09-25 04:27:53

如果您正在使用数据帧并且希望series无法转换为class int错误。使用下面的代码。

new_df= pd.to_datetime(df_new['time'], unit='s')

If you are working with a dataframe and do not want the series cannot be converted to class int error. Use the code below.

new_df= pd.to_datetime(df_new['time'], unit='s')
临走之时 2024-09-25 04:27:53

我刚刚成功使用:

>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date

i just successfully used:

>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date
━╋う一瞬間旳綻放 2024-09-25 04:27:53

您可以使用 easy_date 来简化操作:

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

You can use easy_date to make it easy:

import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")
终止放荡 2024-09-25 04:27:53

又快又脏的一行:

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

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

quick and dirty one liner:

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

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

小忆控 2024-09-25 04:27:53

我使用 pytz 创建一个将 UNIX 日期和时间转换为赫尔辛基时区的函数:

from datetime import datetime, timedelta
from pytz import timezone
import pytz
    
def convert_date_time(unix_date,unix_time):
      utc = pytz.utc
      fmt = '%a %d-%b-%Y'
      time_fmt = '%H:%M:%S'
      utc_dt = utc.localize(datetime.utcfromtimestamp(unix_date))
      utc_time = utc.localize(datetime.utcfromtimestamp(unix_time))
      hki_tz = timezone('Europe/Helsinki') # refer documentation for the TZ adjustments
      hki_dt = utc_dt.astimezone(hki_tz)
      return hki_dt.strftime(fmt), utc_time.strftime(time_fmt)

并获取值:

unixDate = 1706392800
unixTime = 79800
hkiDate, hkiTime = convert_date_time(unixDate,unixTime)
print(f"Today's date and time is: {hkiDate}, {hkiTime}")

输出如下所示:

Today's date and time is: Sun 28-Jan-2024, 22:10:00

I used pytz to create a function that converts the UNIX date and time to Helsinki timezone:

from datetime import datetime, timedelta
from pytz import timezone
import pytz
    
def convert_date_time(unix_date,unix_time):
      utc = pytz.utc
      fmt = '%a %d-%b-%Y'
      time_fmt = '%H:%M:%S'
      utc_dt = utc.localize(datetime.utcfromtimestamp(unix_date))
      utc_time = utc.localize(datetime.utcfromtimestamp(unix_time))
      hki_tz = timezone('Europe/Helsinki') # refer documentation for the TZ adjustments
      hki_dt = utc_dt.astimezone(hki_tz)
      return hki_dt.strftime(fmt), utc_time.strftime(time_fmt)

and to get the values:

unixDate = 1706392800
unixTime = 79800
hkiDate, hkiTime = convert_date_time(unixDate,unixTime)
print(f"Today's date and time is: {hkiDate}, {hkiTime}")

the output looks like this:

Today's date and time is: Sun 28-Jan-2024, 22:10:00
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文