编写一个函数来使用 time_t 显示当前日期?

发布于 2024-08-06 00:23:22 字数 451 浏览 9 评论 0原文

我一直在编写一个时间转换器来获取系统 time_t 并将其转换为人类可读的日期/时间。哦,这是我的第二个 python 脚本。我们将把这个事实放在一边并继续前进。

完整的脚本托管在此处

编写年份和月份的转换器相当容易,但我在努力让这一天工作时遇到了严重的障碍。正如你所看到的,从 1970 年到今天,我一直在尝试暴力破解。不幸的是,这一天的结果为-105。

有谁知道更好的方法,或者解决我在这里尝试的方法?现在是凌晨 3:30,所以我很可能错过了一些明显的事情。

抱歉,我忘记指出我手动执行此操作是为了学习 python。不幸的是,通过日期函数执行此操作达不到目的。

I've been writing a time converter to take the systems time_t and convert it into human readable date/time. Oh, and this is my second python script ever. We'll leave that fact aside and move on.

The full script is hosted here.

Writing converters for the year and month were fairly easy, but I've hit a serious brick wall trying to get the day working. As you can see, I've been trying to brute-force my way all the way from 1970 to today. Unfortunately, the day comes out as -105.

Does anyone know of a better way to do it, or a way to fix up what I have attempted here? It's currently 3:30 AM, so it's quite possible I'm missing something obvious.

Sorry, I forgot to note that I'm doing this manually in order to learn python. Doing it via date functions defeats the purpose, unfortunately.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

猫瑾少女 2024-08-13 00:23:22

为什么不使用:

from datetime import datetime
the_date = datetime.fromtimestamp(the_time)
print(the_date.strftime('%Y %B %d'))

datetime 模块处理所有边缘情况——闰年、闰秒、闰日——以及时区转换(带有可选的第二个参数)

Why not use:

from datetime import datetime
the_date = datetime.fromtimestamp(the_time)
print(the_date.strftime('%Y %B %d'))

The datetime module handles all the edge cases -- leap years, leap seconds, leap days -- as well as time zone conversion (with optional second argument)

纵山崖 2024-08-13 00:23:22

您可以使用 time.strftime

>>> import time
>>> time.strftime('%Y %B %d')
'2009 September 18'

或使用 datetime.date.strftime

>>> import datetime
>>> datetime.date.today().strftime('%Y %B %d')
'2009 September 18'

You could do it either with time.strftime:

>>> import time
>>> time.strftime('%Y %B %d')
'2009 September 18'

or with datetime.date.strftime:

>>> import datetime
>>> datetime.date.today().strftime('%Y %B %d')
'2009 September 18'
吝吻 2024-08-13 00:23:22

(我假设您这样做是为了学习 Python,所以我会指出您代码中的错误)。

>>> years = SecondsSinceEpoch / 31540000

不不不不。你不能那样做。有些年份有 31536000 秒,有些年份有 31622400 秒。

>>> if calendar.isleap(yeariterator) == True:

您不需要测试真值是否为真。 :-) 做:

>>> if calendar.isleap(yeariterator):

相反。

同时更改:

>>> yeariterator = 1969
>>> iterator = 0
>>> while yeariterator < yearsfordayfunction:
>>>     yeariterator = yeariterator + 1

至:

<块引用>
<块引用>

对于范围内的年份迭代器(1970,yearsfordayfunction):


这也将修复你的错误:直到 2009 年之后你才会停止,所以你得到答案 -105,因为一年还剩 105 天。

而且,逐月计算也没有多大意义。年复一年,效果很好。

    for yeariterator in range(1970, yearsfordayfunction):
            if calendar.isleap(yeariterator) == True:
                    days = days - 366
            else:
                    days = days - 365

8 个空格的缩进已经很多了。 4 比较常见。

另外,我会用一种方法计算年份和日期,而不是执行两次。

def YearDay():
    SecondsSinceEpoch = int(time.time())
    days = SecondsSinceEpoch // 86400 # Double slash means floored int.
    year = 1970
    while True:
            if calendar.isleap(year):
                    days -= 366
            else:
                    days -= 365
            year += 1
            if calendar.isleap(year):
                    if days <= 366:
                            return year, days
            else:
                    if days <= 365:
                            return year, days


def MonthDay(year, day):
    if calendar.isleap(year):
            monthstarts = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
    else:
            monthstarts = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]

    month = 0
    for start in monthstarts:
            if start > day:
                    return month, day - monthstarts[month-1] + 1
            month += 1

(I'm assuming you do this to learn Python, so I'll point out the errors in your code).

>>> years = SecondsSinceEpoch / 31540000

Nonononono. You can't do that. Some years have 31536000 seconds, others have 31622400 seconds.

>>> if calendar.isleap(yeariterator) == True:

You don't need to test if a true value is true. :-) Do:

>>> if calendar.isleap(yeariterator):

Instead.

Also change:

>>> yeariterator = 1969
>>> iterator = 0
>>> while yeariterator < yearsfordayfunction:
>>>     yeariterator = yeariterator + 1

To:

for yeariterator in range(1970, yearsfordayfunction):

That will also fix your error: You don't stop until AFTER 2009, so you get the answer -105, because there is 105 days left of the year.

And also, there's not much point in calculating month by month. Year by year works fine.

    for yeariterator in range(1970, yearsfordayfunction):
            if calendar.isleap(yeariterator) == True:
                    days = days - 366
            else:
                    days = days - 365

And an indent of 8 spaces is a lot. 4 is more common.

Also, I'd calculate year and day of year in one method, instead of doing it twice.

def YearDay():
    SecondsSinceEpoch = int(time.time())
    days = SecondsSinceEpoch // 86400 # Double slash means floored int.
    year = 1970
    while True:
            if calendar.isleap(year):
                    days -= 366
            else:
                    days -= 365
            year += 1
            if calendar.isleap(year):
                    if days <= 366:
                            return year, days
            else:
                    if days <= 365:
                            return year, days


def MonthDay(year, day):
    if calendar.isleap(year):
            monthstarts = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
    else:
            monthstarts = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]

    month = 0
    for start in monthstarts:
            if start > day:
                    return month, day - monthstarts[month-1] + 1
            month += 1
甜`诱少女 2024-08-13 00:23:22

我还将指出您发布的代码中的一些奇怪之处:

    try:
            SecondsSinceEpoch = time.time()
    except IOError:
            Print("Unable to get your system time!")

1.)为什么 time.time() 会引发 IOError?据我所知,该函数不可能引发错误,它应该始终返回一个值。

2.) Print 应为print

3.) 即使 time.time 确实引发了 IOError 异常,您也会吞下该异常,而您可能不想这样做。下一行需要定义SecondsSinceEpoch,这样只会引发另一个(更令人困惑的)异常。

I'll also point out something odd in the code you posted:

    try:
            SecondsSinceEpoch = time.time()
    except IOError:
            Print("Unable to get your system time!")

1.) Why would time.time() raise an IOError? As far as I know it's impossible for that function to raise an error, it should always return a value.

2.) Print should be print.

3.) Even if time.time did raise an IOError exception, you are swallowing the exception, which you probably don't want to do. The next line requires SecondsSinceEpoch to be defined, so that will just raise another (more confusing) exception.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文