自纪元以来将时间字符串存储到μ中

时间:2017-03-27 09:06:47

标签: python python-3.x datetime calendar

我正在尝试将datetime.time字符串转换为等于python中的总微秒的整数。

# my input
>>> mark_raw = '00:01:00.420000' # 0 hr, 1 min, 0 sec, 42 ms

# my desired output
>>> mark_time 
60420000

我目前的计划发现了自纪元以来的日期时间与纪元以来的日期

之间的差异
# 0 hr, 1 min, 0 sec, 42 ms
>>> mark_raw = '00:01:00.420000'
>>> mark_dt = datetime.strptime(mark_raw, '%H:%M:%S.%f')

>>> mark_dt
datetime.datetime(1900, 1, 1, 0, 1, 0, 420000)

>>> mark_date  = mark_dt.date()
>>> mark_date
datetime.date(1900, 1, 1)

>>> dt_epoch = calendar.timegm(mark_dt.timetuple()) * 1000
>>> dt_epoch
-2208988740000

>>> date_epoch = calendar.timegm(mark_date.timetuple())  * 1000
>>> date_epoch
-2208988800000

>>> mark_time = dt_epoch - date_epoch
>>> mark_time
60000

不确定我为什么得到60000微秒。也许是四舍五入的问题?我假设datetime.date(1900, 1, 1)等于datetime.date(1900, 1, 1, 0, 0, 0, 0),但也许情况并非如此。

唯一的要求是将原始时间字符串设置为微秒,对任何其他策略开放,任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:2)

不匹配的原因是,

>>> mark_dt.timetuple()
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=1, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
>>> mark_date.timetuple()
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)

你可以在这看到差异! tm_min=1中的mark_dt.timetuple()tm_min=0中的mark_date.timetuple()

dt_epoch = calendar.timegm(mark_dt.timetuple()) 
print dt_epoch

date_epoch = calendar.timegm(mark_date.timetuple())  
print date_epoch

mark_time = dt_epoch - date_epoch
print mark_time

将打印

-2208988740
-2208988800
60

从而反映了两个结果中的tm_min = 1和0差异!

获取微秒

并且,如果你想获得微秒,从epoch获得timedelta,找到total_seconds,然后乘以10 ^ -6即1e6

# 0 hr, 1 min, 0 sec, 42 ms
import datetime
import calendar
mark_raw = '00:01:00.420000'
mark_dt = datetime.datetime.strptime(mark_raw, '%H:%M:%S.%f')

mark_date = mark_dt.date()
epoch_datetime=datetime.datetime(
    year=mark_date.year, 
    month=mark_date.month,
    day=mark_date.day,
)
print (mark_dt - epoch_datetime).total_seconds()*(1000000) 
#print (mark_dt - epoch_datetime).total_seconds()*ie6

<强>输出:

60420000.0
希望它有所帮助!

答案 1 :(得分:0)

您可以将calendar.timegm更改为.timestamp()

>>> calendar.timegm(mark_dt.timetuple()) * 1000
-2208988740000
>>> mark_dt.timestamp() * 1000
-2208988739.58

Keerthana的答案已经解释了日期时间问题的原因。

相关问题