相关文章推荐
紧张的凳子  ·  日期时间格式化·  1 月前    · 
冷静的豌豆  ·  mysql ...·  2 周前    · 
闷骚的伤疤  ·  Antibody Probes of ...·  1 年前    · 
谈吐大方的爆米花  ·  vue ...·  1 年前    · 

做开发中难免时间类型之间的转换, 最近就发现前端js和后端django经常要用到这个转换, 其中jsDate.now()精确到毫秒,而Python中Datetime.datetime.now()是精确到微秒的。

1. 字符串日期时间转换成时间戳

# '2015-08-28 16:43:37.283' --> 1440751417.283
# 或者 '2015-08-28 16:43:37' --> 1440751417.0
def string2timestamp(strValue):
        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.时间戳转换成字符串日期时间

# 1440751417.283 --> '2015-08-28 16:43:37.283'
def timestamp2string(timeStamp):
        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 ''
1. 字符串日期时间转换成时间戳# '2015-08-28 16:43:37.283' --> 1440751417.283# 或者 '2015-08-28 16:43:37' --> 1440751417.0def string2timestamp(strValue): try: d = datetime.datetime.strptim # '2015-08-28 16:43:37.283' --> 1440751417.283 # 或者 '2015-08-28 16:43:37' --> 1440751417.0 def string2 timestamp (strValue): try: ... # 使用time timeStamp = time.time() # 1559286774.2953627 timeArray = time.localtime( timeStamp ) otherStyleTime = time.strfti
Python 中的 timestamp 是指Unix 时间戳 ,表示从1970年1月1日0时0分0秒(UTC)至当前时间的秒数。而 datetime 表示日期和时间的 Python 标准库。 要将 timestamp 转换 datetime ,可以使用 Python 内置的 datetime 模块中的from timestamp ()函数。该函数可以将 timestamp 转换 datetime 对象(即日期时间类型),并以本地时间(默认)显示。 以下是一个简单的示例代码,用于将当前时间的 timestamp 转换 datetime : ``` python import datetime # 导入 datetime 模块 timestamp = 1609459200 # 假设我们要 转换 timestamp 为2021年1月1日0时0分0秒(UTC)的 时间戳 datetime _obj = datetime . datetime .from timestamp ( timestamp ) # from timestamp ()函数 转换 datetime 对象 print( datetime _obj) # 输出:2021-01-01 08:00:00(因为我们运行的环境为UTC+8,与世界标准时间相差8个小时) 从上述示例代码中可以看出,只需使用 datetime . datetime .from timestamp ()函数并传入 timestamp 参数即可将其 转换 datetime 对象。值得注意的是,from timestamp ()函数的参数默认是本地时区的UNIX 时间戳 。如果你要指定其他时区,请参考 datetime 库中的其他函数和参数。 总之,使用 Python 内置的 datetime 模块中的from timestamp ()函数,可以将 timestamp 转换 datetime 类型,以更方便地处理日期和时间。