The conversion between Python timestamp and datetime

Source: Internet
Author: User

In the development of unavoidable time-type conversion between the recent discovery front-end JS and back-end Django often use this conversion, where Jsdate.now () accurate to milliseconds, while Python Datetime.datetime.now () is accurate to microseconds.


1. String date time conversion to timestamp

# ' 2015-08-28 16:43:37.283 '-and 1440751417.283# or ' 2015-08-28 16:43:37 '-1440751417.0def string2timestamp ( strvalue):    try:                d = datetime.datetime.strptime (strvalue, "%y-%m-%d%h:%m:%s.%f")        t = d.timetuple ()        timeStamp = Int (time.mktime (t))        TimeStamp = float (str (timeStamp) + str ("%06d"% D.microsecond))/1000000        Print TimeStamp        return timeStamp    except ValueError as e:        print e        d = datetime.datetime.strptime (str2, "%y-% m-%d%h:%m:%s ")        t = d.timetuple ()        timeStamp = Int (time.mktime (t))        TimeStamp = float (str (timeStamp) + str ("%06d"% D.microsecond)) /1000000        print TimeStamp        return TimeStamp


2. Timestamp converted to string date time

# 1440751417.283 to ' 2015-08-28 16:43:37.283 ' def timestamp2string (timeStamp):    try:        d = Datetime.datetime.fromtimestamp (timeStamp)        str1 = D.strftime ("%y-%m-%d%h:%m:%s.%f")        # 2015-08-28 16:43:37.283000 '        return str1    except Exception as e:        print e        return '

Copyright NOTICE: This article for Bo Master original article, welcome reprint, reproduced please indicate the source.

The conversion between Python timestamp and datetime

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.