我是python的新手,想编写一个程序,需要在日期和时间的字符串和整数表示之间进行转换.
格式是固定的,必须看起来像"02.03.2010 13:32:20"
有比这更简洁的方式吗?
class TimeStamp:
def __init__(self, day, month, year, hour, minute, second):
self.day = day
self.month = month
self.year = year
self.hour = hour
self.minute = minute
self.second = second
def __repr__(self):
string = ""
if self.day < 10:
string += "0" + str(self.day)
else:
string += str(self.day)
string += "."
if self.month < 10:
string += "0" + str(self.month)
else:
string += str(self.month)
string += "."
if self.year < 10:
string += "0" + str(self.year)
else:
string += str(self.year)
string += " "
if self.hour < 10:
string += "0" + str(self.hour)
else:
string += str(self.hour)
string += ":"
if self.hour < 10:
string += "0" + str(self.hour)
else:
string += str(self.hour)
string += ":"
if self.hour < 10:
string += "0" + str(self.hour)
else:
string += str(self.hour)
return string
Run Code Online (Sandbox Code Playgroud)
改用datetime模块; 它.strftime可以轻松满足您的需求和更多.
>>> from datetime import datetime
>>> datetime.now().strftime('%d.%m.%Y %H:%M:%S')
'08.07.2012 14:43:58'
>>> datetime(2010, 3, 2, 13, 32, 20).strftime('%d.%m.%Y %H:%M:%S')
'02.03.2010 13:32:20'
Run Code Online (Sandbox Code Playgroud)