python 时间字符串相互转换

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/baidu_39416074/article/details/83038576
# 任意时间字符串转换时间对象
from dateutil import parser
time_string = '20181012151855'
datetime_struct = parser.parse(time_string)
time_paid = datetime_struct.strftime('%Y-%m-%d %H:%M:%S')


# 当天0点时间戳
import time
temp_timestamp = time.mktime(
    time.strptime(time.strftime('%Y-%m-%d 00:00:00', time.localtime(time.time())),
                  '%Y-%m-%d %H:%M:%S'))
# 当前时间戳
timestamp = time.time()
timestring = '2016-12-21 10:22:56'  # 时间字符串转为时间戳
timestamp = time.mktime(time.strptime(timestring, '%Y-%m-%d %H:%M:%S'))  # 1482286976.0


# 时间戳转datetime  "2018-10-13 14:23:43.861477"
import datetime
# 当前时间datetime
now = datetime.datetime.now()
datetime_struct = datetime.datetime.fromtimestamp(timestamp)
#  时间差计算  几天/周前/后
three_days_ago = datetime_struct + datetime.timedelta(days=-3)
one_week_ago = datetime_struct + datetime.timedelta(weeks=-1)
three_days_later = datetime_struct + datetime.timedelta(days=3)
# datetime 转为时间
ret_time = datetime_struct.strftime('%Y-%m-%d %H:%M:%S')


# 获取当前时间
now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
year = time.localtime().tm_year  # tm_year,tm_mon,tm_mday,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst


# 查询本周内的数据
cur_time = datetime.datetime.today()
day_num = cur_time.isoweekday()  # 当前天 显示当前日期是本周第几天
monday = (cur_time - datetime.timedelta(days=day_num))
'''contacts = Zlh_list_contacts.objects.filter(create_time__range=(monday, now_time))'''


# 计算时间戳差
from datetime import timedelta
from celery.schedules import crontab
def time_stamp(param):
    pub_time = str(datetime.datetime.strptime(str(param), '%Y-%m-%d %H:%M:%S'))
    local_time = str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))  # 当前时间
    d1 = datetime.datetime.strptime(pub_time, '%Y-%m-%d %H:%M:%S')
    d2 = datetime.datetime.strptime(local_time, '%Y-%m-%d %H:%M:%S')
    delta = d2 - d1  # 时间戳差
    # days,seconds, microseconds, milliseconds, minutes,hours,weeks
    # if delta > datetime.timedelta(minutes=1):
    arg = {
        u'pay_detail过期时限 任务': {
            "task": "djcelery_tasks.task.pay_detail_off",
            'schedule': timedelta(seconds=1),
            "args": (),
        },
        u'试用期结束状态改变 任务': {
            "task": "djcelery_tasks.task.change_service_status",
            'schedule': crontab(hour=u'10,14', minute=30),
            "args": (),
        },
    }
    return delta

 

展开阅读全文

没有更多推荐了,返回首页