Convert datetime object to milliseconds since epoch in Python

文章推薦指數: 80 %
投票人數:10人

A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time ... Skiptocontent ThispostwilldiscusshowtoconvertthedatetimeobjecttomillisecondssincetheepochinPython. 1.Usingtimedelta.total_seconds()function AsimplesolutionistogetthetimedeltaobjectbyfindingthedifferenceofthegivendatetimewithEpochtime,i.e.,midnight1January1970.Toobtaintimeinmilliseconds,youcanusethetimedelta.total_seconds()*1000. 1234567891011 fromdatetimeimportdatetime deftimestamp(dt):    epoch=datetime.utcfromtimestamp(0)    return(dt-epoch).total_seconds()*1000.0 if__name__=='__main__':     dt=datetime(2020,1,1)    print(timestamp(dt))  Download  RunCode 2.Usingdatetime.timestamp()function StartingwithPython3.3,youcanusethedatetime.timestamp()functiontogettheEpochtimestampinsecondsasafloating-pointnumber.Sincedatetimeinstancesareassumedtorepresentlocaltime,youshouldfirstconvertthedatetimeobjecttoUTC.Thiscanbedonewithdt.replace(tzinfo=timezone.utc). 12345678910 fromdatetimeimportdatetime,timezone deftimestamp(dt):    returndt.replace(tzinfo=timezone.utc).timestamp()*1000 if__name__=='__main__':     dt=datetime(2020,1,1)    print(timestamp(dt))  Download  RunCode 3.Usingdeloreanmodule Ifyou’realreadyusingthedeloreanmodule,considerusingitsepochattribute,whichreturnsEpochtimeinseconds. 1234567891011 fromdatetimeimportdatetimeimportdelorean deftimestamp(dt):    returndelorean.Delorean(dt,timezone='UTC').epoch*1000 if__name__=='__main__':     dt=datetime(2020,1,1)    print(timestamp(dt))  Download  RunCode That’sallaboutconvertingdatetimeobjectstomillisecondssincetheepochinPython. RatethispostSubmitRatingAveragerating5/5.Votecount:21Novotessofar!Bethefirsttoratethispost.Wearesorrythatthispostwasnotusefulforyou!Tellushowwecanimprovethispost?SubmitFeedback Thanksforreading. PleaseuseouronlinecompilertopostcodeincommentsusingC,C++,Java,Python,JavaScript,C#,PHP,andmanymorepopularprogramminglanguages. Likeus?Referustoyourfriendsandhelpusgrow.Happycoding🙂 Subscribe Notifyof newfollow-upcomments newrepliestomycomments Name* Email* Name* Email* 0Comments InlineFeedbacks Viewallcomments LoadMoreComments BrowseAlgorithm Amazon Beginner BinarySearch BitHacks Bottom-up Breadth-firstsearch Depth-firstsearch Easy FIFO Greedy Hard Hashing LIFO Maze Medium Microsoft MustKnow PriorityQueue Recursive SlidingWindow Top-down Trie Subscribetonewposts Enteryouremailaddresstosubscribetonewposts. EmailAddress Subscribe Thiswebsiteusescookies.Byusingthissiteyouagreetotheuseofcookies,ourpolicies,copyrighttermsandotherconditions.Readour PrivacyPolicy. DoNOTfollowthislinkoryouwillbebannedfromthesite! Insert



請為這篇文章評分?