简体   繁体   English

Python:将日期时间戳转换为纪元Unix时间并找出剩余天数?

[英]python: convert date timestamp to epoch unix time and figure out number of days remaining?

I want to convert 2014-08-14 20:01:28.242 into a unix timestamp 245293529385 and subtract this by the current timestamp in order to figure out how many days have past and are ultimately remaining by subtracting this value from 14. 我想将2014-08-14 20:01:28.242转换为unix时间戳记245293529385然后将其减去当前时间戳记,以便计算出过去多少天,最后通过从14中减去该值来最终剩余。

Scenario: user signs up and I want to count down the number of days remaining in their trial. 方案:用户注册,我想倒计时剩余的试用天数。

time.strptime to the rescue! time.strptime进行救援! Use the format string %Y-%m-%d %H:%M:%S.%f . 使用格式字符串%Y-%m-%d %H:%M:%S.%f For example: 例如:

   import time
   t = '2014-08-14 20:01:28.242'
   ts = time.strptime(t, '%Y-%m-%d  %H:%M:%S.%f')
   timestamp = time.mktime(ts)

Now to convert it to a datetime (from: How do you convert a Python time.struct_time object into a datetime object? ): 现在将其转换为日期时间(来自: 如何将Python time.struct_time对象转换为日期时间对象? ):

   from datetime import datetime
   dt = datetime.fromtimestamp(timestamp)

There are two parts: 有两个部分:

Convert input time string into datetime object 将输入时间字符串转换为日期时间对象

#!/usr/bin/env python
from datetime import datetime

dt = datetime.strptime('2014-08-14 20:01:28.242', '%Y-%m-%d  %H:%M:%S.%f')

Convert datetime object to Unix time ("seconds since epoch") 将datetime对象转换为Unix时间(“自纪元以来的秒数”)

The result depends on what time zone is used for the input time eg, if the input is in UTC then the corresponding POSIX timestamp is: 结果取决于输入时间使用哪个时区,例如,如果输入采用UTC,则相应的POSIX时间戳为:

timestamp = (dt - datetime(1970,1,1)).total_seconds()
# -> 1408046488.242

If your input is in the local timezone then see How do I convert local time to UTC in Python? 如果您的输入位于本地时区,请参阅如何在Python中将本地时间转换为UTC?

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

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