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