我正在尝试将如下所示的字符串秒动态转换为字符串日期。
'1545239561 +0100'
问题是在最后插入了时区,我找不到任何使用正确格式从此字符串中检索日期的python时间对象方法。
我的尝试:
>>>seconds = '1545239561 +0100'
>>>time.strftime('%y%m%d-%H%M%S-%f', datetime.datetime.fromtimestamp(seconds)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required (got type str)
>>>time.strptime(seconds)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/3.6.4_3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 559, in _strptime_time
tt = _strptime(data_string, format)[0]
File "/usr/local/Cellar/python/3.6.4_3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data '1545239561 +0100' does not match format '%a %b %d %H:%M:%S %Y'
>>>time.strptime(seconds, "%S +%Z")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/3.6.4_3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 559, in _strptime_time
tt = _strptime(data_string, format)[0]
File "/usr/local/Cellar/python/3.6.4_3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data '1545239561 +0100' does not match format '%S +%Z'
答案 0 :(得分:1)
我会尝试分别处理这两个值,然后将它们合并为一个import setuptools
from distutils.command.build import build as build_orig
class build(build_orig):
def finalize_options(self):
super().finalize_options()
# I stole this line from ead's answer:
__builtins__.__NUMPY_SETUP__ = False
import numpy
# or just modify my_c_lib_ext directly here, ext_modules should contain a reference anyway
extension = next(m for m in self.distribution.ext_modules if m == my_c_lib_ext)
extension.include_dirs.append(numpy.get_include())
my_c_lib_ext = setuptools.Extension(
name="my_c_lib",
sources=["my_c_lib/some_file.pyx"]
)
setuptools.setup(
...,
ext_modules=[my_c_lib_ext],
cmdclass={'build': build},
...
)
:
datetime
答案 1 :(得分:1)
是@mfrackwiak ...
我做到了
>>> epoch = "1545239561 +0100"
>>> seconds, offset = epoch.split()
>>> datetime.fromtimestamp(int(seconds)).replace(tzinfo=datetime.strptime(offset, "%z").tzinfo).strftime('%Y-%m-%d %H:%M:%S-%Z')
'2018-12-19 18:12:41-UTC+01:00'
>>>
答案 2 :(得分:0)
您可以尝试以下示例:
from datetime import datetime,timedelta
# split the timevalue and offset value
ss = '1545239561 +0100'.split()
format = "%A, %B %d, %Y %I:%M:%S"
# calculate the hour and min in the offset
hour = int(ss[1][0:2])
min = int(ss[1][2:])
# calculate the time from the sec and convert it to datetime object
time_from_sec = datetime.strptime(datetime.fromtimestamp(int(ss[0])).strftime(
format), format)
# add the offset delta value to the time calculated
time_with_delta_added = time_from_sec + timedelta(hours=hour,minutes=min)
print(time_with_delta_added)
输出:
2018-12-19 12:22:41