我有一组变量repeatElements :: [(Int, a)] -> -- insert result type
repeatElements [] = -- insert result for empty list base case
repeatElements ((n, x):xs) = repeatAnElement n x -- insert part that recurses
where
repeatAnElement :: Int -> a -> -- insert result type
repeatAnElement 0 ch = -- insert result for zero-needed base case
repeatAnElement n ch = -- insert result for recursive case
,可以根据字符串格式随机传递这些变量,我正在将其转换为所需的日期格式(epoch_time,normal_date,date_time,date_time_zone)
。我的变量可以是带有纪元值的字符串或带有日期时区的字符串或带有日期时间或仅日期的字符串。我尝试了以下方式,并且始终只以allowed_date_formats形式进入第一项。有人可以建议我一种更好的方法还是可以帮助我解决问题。
(%Y-%m-%d)
我遇到的错误是
from datetime import datetime
epoch_time='1481883402'
normal_date="2014-09-03"
date_time=str("2014-05-12 00:00:00")
date_time_zone=str("2015-01-20 08:28:16 UTC")
OP_FORMAT="%Y-%m-%d"
ALLOWED_STRING_FORMATS=["%Y-%m-%d %H:%M:%S %Z","%Y-%m-%d %H:%M:%S","%Y-%m-%d"]
def convert_timestamp(date_timestamp=None):
for format in ALLOWED_STRING_FORMATS:
if datetime.strptime(date_timestamp,format):
d=datetime.strptime(date_timestamp,"%Y-%m-%d")
else:
d = datetime.fromtimestamp((float(date_timestamp) / 1000.), tz=None)
return d.strftime(OP_FORMAT)
print(convert_timestamp(normal_date))
答案 0 :(得分:3)
您可以使用try-except。
def convert_timestamp(date_timestamp, output_format="%Y-%m-%d"):
ALLOWED_STRING_FORMATS=[
"%Y-%m-%d %H:%M:%S %Z",
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d",
]
for format in ALLOWED_STRING_FORMATS:
try:
d = datetime.strptime(date_timestamp,format):
return d.strftime(output_format)
except ValueError:
pass
try:
# unix epoch timestamp
epoch = int(date_timestamp) / 1000
return datetime.fromtimestamp(epoch).strftime(output_format)
except ValueError:
raise ValueError('The timestamp did not match any of the allowed formats')
答案 1 :(得分:1)
您是否需要确保仅允许使用特定格式?
否则,您可能会考虑使用dateutil中的自动解析器:
from dateutil import parser
normal_date="2014-09-03"
print(parser.parse(normal_date))