编写一个python脚本,在每天的给定时间生成一个时间戳(unix epoch值) [英] Write a python script to generate a timestamp ( unix epoch value) each day at a give time

查看:33
本文介绍了编写一个python脚本,在每天的给定时间生成一个时间戳(unix epoch值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个小型 python,它需要在每天下午 1 点的特定时间生成一个简单的精确时间戳(脚本将每天运行).我是这样写的:

from datetime import datetimenow = datetime.utcnow() # 当前时间then = datetime(1970,1,1) # 0 纪元时间ts = 现在 - 然后ts = ts.days * 24 * 3600 + ts.seconds打印 ts

这很好,但我想通过 now 作为我每天的 time_field.我该怎么做?

解决方案

你可以使用time.mktime函数:

<预><代码>>>>导入日期时间>>>导入时间>>>dt = datetime.datetime.today().replace(小时=13,分钟=0,秒=0,微秒=0)>>>打印(dt)2016-04-06 13:00:00>>>time.mktime(dt.timetuple())1459944000.0

如果您需要时区感知,请使用时区感知日期时间的 utctimetuple 方法和 time.gmtime 函数.

(编辑以显示如何为特定时间创建 datetime.datetime)

I want to write a small python which needs to generate a simple precise timestamp each day ( the script will be run each day) at a particular hour say 1pm. I wrote something like this:

from datetime import datetime
now = datetime.utcnow() # Current time
then = datetime(1970,1,1) # 0 epoch time
ts = now - then
ts = ts.days * 24 * 3600 + ts.seconds
print ts

This is good, but i want to pass now for the time_field that i on daily basis. How do I do this?

解决方案

You can use the time.mktime function:

>>> import datetime
>>> import time
>>> dt = datetime.datetime.today().replace(hour=13, minute=0, second=0, microsecond=0)
>>> print(dt)
2016-04-06 13:00:00
>>> time.mktime(dt.timetuple())
1459944000.0

If you need to be timezone-aware, use a timezone-aware datetime's utctimetuple method and the time.gmtime function.

(edited to show how to create datetime.datetime for a specific time)

这篇关于编写一个python脚本,在每天的给定时间生成一个时间戳(unix epoch值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆