Details of conversion between python timestamp and datetime
- 2020-06-15 09:37:06
- OfStack
It's hard to avoid conversion between time types in development, and it's recently been found that front-end js and back-end django often use this conversion, where jsDate.now () is accurate to milliseconds and Datetime.datetime.now () is accurate to microseconds.
1. String date time converted to timestamp
# '2015-08-28 16:43:37.283' --> 1440751417.283
# or '2015-08-28 16:43:37' --> 1440751417.0
def 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. The timestamp is converted to a string date time
# 1440751417.283 --> '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 ''