关于python:将大纪元时间转换为日期时间

Converting Epoch time into the datetime

我从其他人那里得到的回应是一种划时代的格式,就像

1
2
start_time = 1234566
end_time = 1234578

我想将那个epoch秒转换为mysql格式的时间,这样我就可以将这些差异存储在mysql数据库中。

我尝试过:

1
2
3
>>> import time
>>> time.gmtime(123456)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=2, tm_hour=10, tm_min=17, tm_sec=36, tm_wday=4, tm_yday=2, tm_isdst=0)

上面的结果不是我所期望的。我想要像

1
2012-09-12 21:00:00

请建议我如何做到这一点?

也,为什么我要找TypeError: a float is required

1
2
3
4
5
>>> getbbb_class.end_time = 1347516459425
>>> mend = time.gmtime(getbbb_class.end_time).tm_hour
Traceback (most recent call last):
  ...
TypeError: a float is required


转换你的时间价值(或浮或int)的格式化字符串,使用:

1
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))


所以,你可以使用datetime

1
2
3
>>> import datetime
>>> datetime.datetime.fromtimestamp(1347517370).strftime('%c')
  '2012-09-13 02:22:50'


1
2
3
>>> import datetime
>>> datetime.datetime.fromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
'2012-09-13 14:22:50' # Local time

让UTC。

1
2
>>> datetime.datetime.utcfromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
  '2012-09-13 06:22:50'

这是你需要的

1
2
3
4
5
In [1]: time.time()
Out[1]: 1347517739.44904

In [2]: time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time()))
Out[2]: '2012-09-13 06:31:43'

请输入a float不是在int和其他TypeError应该走开。

1
mend = time.gmtime(float(getbbb_class.end_time)).tm_hour

试试这个:

1
2
3
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(1347517119))
'2012-09-12 23:18:39'

所以,你可以在MySQL,FROM_UNIXTIME样:

1
INSERT INTO tblname VALUES (FROM_UNIXTIME(1347517119))

你的第二个,因为它是可能的getbbb_class.end_timeis a字符串。你可以把它的数字float(getbbb_class.end_time)样:


1
2
3
4
5
6
7
8
9
10
11
#This adds 10 seconds from now.
from datetime import datetime
import commands

date_string_command="date +%s"
utc = commands.getoutput(date_string_command)
a_date=datetime.fromtimestamp(float(int(utc))).strftime('%Y-%m-%d %H:%M:%S')
print('a_date:'+a_date)
utc = int(utc)+10
b_date=datetime.fromtimestamp(float(utc)).strftime('%Y-%m-%d %H:%M:%S')
print('b_date:'+b_date)

这是美好的,但它更多的是来自于Unix的命令的日期。


在第一位的是信息时代和gmtime

1
2
3
The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar  time.   When  inter-
       preted  as  an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal
       Time (UTC).

明白,应该是知识时代。

1
2
3
4
>>> time.time()
1347517171.6514659
>>> time.gmtime(time.time())
(2012, 9, 13, 6, 19, 34, 3, 257, 0)

只是确保你传递到time.gmtime()arg是整数。