简体   繁体   English

如何在Python中生成昨天和今天午夜的POSIX值?

[英]How can I generate POSIX values for yesterday and today at midnight in Python?

I've been struggling to determine how I can generate a POSIX (UNIX) time value for today and yesterday (midnight) via Python. 我一直在努力确定如何通过Python为今天和昨天(午夜)生成POSIX(UNIX)时间值。 I created this code, but keep stumbling with how to convert them to a POSIX value: 我创建了这段代码,但是如何将它们转换为POSIX值仍然存在争议:

from datetime import datetime, timedelta
import time
today_string = datetime.now().strftime('%Y-%m-%d 00:00:00')
yesterday_string = (datetime.now() - timedelta(0)).strftime('%Y-%m-%d 00:00:00')

today = datetime.strptime(today_string, '%Y-%m-%d %H:%M:%S')
yesterday = datetime.strptime(yesterday_string, '%Y-%m-%d %H:%M:%S')

print time.mktime(today).timetuple()

This code yields an exception: 此代码产生一个异常:

TypeError: argument must be 9-item sequence, not datetime.datetime

At this point, I'm at my wits end. 在这一点上,我在我的智慧结束。 Any help you can provide is appreciated. 您可以提供的任何帮助表示赞赏。

You should apply the timetuple() method to the today object, not to the result of time.mktime(today) : 您应该将timetuple()方法应用于today对象,而不是time.mktime(today)的结果:

>>> time.mktime(today.timetuple())
1345845600.0

By the way, I'm wrong or yesterday will be equal to today in your code? 顺便说一下,我错了,或者yesterday在你的代码中等于today

edit: To obtain the POSIX time for today you can simply do: 编辑:要获得今天的POSIX时间,您可以简单地执行以下操作:

time.mktime(datetime.date.today().timetuple())

@Bakuriu is right here. @Bakuriu就在这里。 But you are making this overcomplex. 但你正在使这个过于复杂。

Take a look at this: 看看这个:

from datetime import date, timedelta
import time

today = date.today()
today_unix = time.mktime(today.timetuple())

yesterday = today - timedelta(1)
yesterday_unix = time.mktime(yesterday.timetuple())

Since the date object doesn't hold time, it resets it to the midnight. 由于date对象没有时间,因此将其重置为午夜。

You could also replace the last part with: 你也可以用以下代码替换最后一部分:

yesterday_unix = today_unix - 86400

but note that it wouldn't work correctly across daylight saving time switches (ie you'll end up with 1 AM or 23 PM). 但请注意,它不能在夏令时开关之间正常工作(即最终会在凌晨1点或23点结束)。

Getting a unix timestamp from a datetime object as a string and as a float: 从datetime对象获取unix时间戳作为字符串和float:

datetime.now().strftime('%s')
'1345884732'

time.mktime(datetime.now().timetuple())
1345884732.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM