Python: Converting string to timestamp with microseconds

前端 未结 3 1796
南旧
南旧 2020-12-31 10:32

I would like to convert string date format to timestamp with microseconds I try the following but not giving expected result:

\"\"\"input string date ->          


        
3条回答
  •  轮回少年
    2020-12-31 11:10

    There is no slot for the microseconds component in a time tuple:

    >>> import time
    >>> import datetime
    >>> myDate = "2014-08-01 04:41:52,117"
    >>> datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f").timetuple()
    time.struct_time(tm_year=2014, tm_mon=8, tm_mday=1, tm_hour=4, tm_min=41, tm_sec=52, tm_wday=4, tm_yday=213, tm_isdst=-1)
    

    You'll have to add those manually:

    >>> dt = datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
    >>> time.mktime(dt.timetuple()) + (dt.microsecond / 1000000.0)
    1406864512.117
    

    The other method you could follow is to produce a timedelta() object relative to the epoch, then get the timestamp with the timedelta.total_seconds() method:

    epoch = datetime.datetime.fromtimestamp(0)
    (dt - epoch).total_seconds()
    

    The use of a local time epoch is quite deliberate since you have a naive (not timezone-aware) datetime value. This method can be inaccurate based on the history of your local timezone however, see J.F. Sebastian's comment. You'd have to convert the naive datetime value to a timezone-aware datetime value first using your local timezone before subtracting a timezone-aware epoch.

    As such, it is easier to stick to the timetuple() + microseconds approach.

    Demo:

    >>> dt = datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
    >>> epoch = datetime.datetime.fromtimestamp(0)
    >>> (dt - epoch).total_seconds()
    1406864512.117
    

提交回复
热议问题