簡體   English   中英

將整數時間/日期轉換為字符串的更整潔的方法

[英]Neater way of converting an integer time/date to a string

我是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

改用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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM