kian
kian

Reputation: 87

Convert date and time to time stamp

I have a text file ,want to open in python and take the date and time (in header) then change it to seconds (timestamp). but result is not the same as online websites. Code:

with open('sample for north - Kopie.txt', "r") as f:
    content = f.readlines()

    for x in content :
        day = float (content [0][:2])
        month = float (content [0][3:5])
        year = float (content [0][6:10])
        hour = float (content [0][10:13])
        minn = float (content [0][14:16])
        second = float (content [0][17:19])
        time = float ((((year-1970)*31556926)+((month-1)*2629743)+((day-1)*86400)+((hour)*3600)+((minn)*60)+second))

for 13.07.2015 09:38:17 result of program is 1436911625 but result of websites are 1436780297.

Upvotes: 3

Views: 4918

Answers (2)

jfs
jfs

Reputation: 414079

There are two parts:

  1. Convert a time string into a time object in Python. You could use .strptime() for that:

    from datetime import datetime
    
    dt = datetime.strptime("13.07.2015 09:38:17", "%d.%m.%Y %H:%M:%S")
    # -> datetime.datetime(2015, 7, 13, 9, 38, 17)
    
  2. Convert the time object into (POSIX) timestamp (Unix time). 1436780297 result suggests that your input time is in UTC and therefore you could use calendar.timegm() to get the timestamp:

    from calendar import timegm
    
    timestamp = timegm(dt.timetuple())
    # -> 1436780297
    

See Converting datetime.date to UTC timestamp in Python

Upvotes: 2

mmachine
mmachine

Reputation: 926

You may use time module:

import time

>>>print(time.mktime(time.strptime("13.07.2015 09:38:17", "%d.%m.%Y %H:%M:%S")))
1436769497.0

Upvotes: 4

Related Questions