Python Time Module Temporal conversion

Source: Internet
Author: User

Get current time

Gets the current time stamp

time_now = int(time.time())  #时间戳  # 1529461333
Format time
import timecurrent_time=time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime(time.time()))current_hour=time.strftime(‘%H‘,time.localtime(time.time()))#输出格式: ‘2018-06-20 10:20:19‘
Database DateTime format support.
current_time=time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime(time.time()))#在数据库中,字段可以是varchar而不是datetime
Convert Timestamp to TIME
a=1490931508time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime(a))
Convert time to time stamp
c=‘2017-03-31 11:38:28‘d=time.strptime(c,‘%Y-%m-%d %H:%M:%S‘)time.mktime(d)
JSON serializes a datetime field in MySQL
from bson import json_utilimport jsonjson.dumps(anObject, default=json_util.default)json.loads(aJsonString, object_hook=json_util.object_hook)
Time Operation:

Method One:

        time1 = datetime.datetime.now()        time2 = datetime.datetime.now()        seconds = (time2 - time1).seconds        print ‘seconds‘,seconds

Method Two:

        #先获得时间数组格式的日期        oneDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 1))        #minutes, days, months,        #转换为时间戳:        timeStamp = int(time.mktime(oneDayAgo.timetuple()))          #转换为其他字符串格式:        time1 = oneDayAgo.strftime("%Y-%m-%d %H:%M:%S")        time2 =  host.update_time        if time2 > time1:            print "正常"        else:            print "未上报"

Python Time Module Temporal conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.