简体   繁体   English

如何将Python日期时间对象转换为时间戳而没有时间和时间倒退?

[英]How to convert a Python datetime object into timestamp without time and backwards?

I am making a timestamp out of a datetime object without minutes, seconds and so on: 我用datetime对象制作了一个时间戳,没有分钟,秒等:

import datetime
import time
import pytz
today_timestamp = datetime.datetime.now(pytz.timezone('Europe/Moscow')).replace(hour=0, minute=0,second=0, microsecond=0).timestamp()

And as a result I get: 结果,我得到:

1506546000.0

Then I am making a timestamp out of a string type object: 然后,我使用字符串类型的对象制作时间戳记:

str_to_time = time.strptime('28.09.17', '%d.%m.%y')
time_to_timestamp = time.mktime(str_to_time)

And I get: 我得到:

1506556800.0

I put the today's date in a string. 我将今天的日期放在字符串中。 Why these numbers are different? 为什么这些数字不同?

time.strptime uses whatever timezone it inherited from the process that started the python process. time.strptime使用它从启动python进程的进程继承的任何时区。 Likely the timezone that was set when python was launched is not Europe/Moscow , but UTC . 启动python时设置的时区可能不是Europe/Moscow ,而是UTC Did you have TZ=UTC set when launching the python interpreter? 启动python解释器时是否设置了TZ=UTC

today_timestamp = datetime.datetime.now(pytz.timezone('UTC')).replace(hour=0, minute=0,second=0, microsecond=0).timestamp()
1506556800.0

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

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