By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,994 Members | 2,073 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,994 IT Pros & Developers. It's quick & easy.

How bi-directional convert request data to Unix timestamp in Python?

P: 1
I have a string variable string of the date:
data = "24.01.2014 15:25:45"
How convert this data to Unix timestamp and back?
Which Python commands?
Thank you very much!
Jan 24 '14 #1

✓ answered by bvdet

This can be done with the time and datetime modules. Use time.strptime to create struct_time objects. Example:
Expand|Select|Wrap|Line Numbers
  1. timeObj = time.strptime(data, "%d.%m.%Y %H:%M:%S")
To determine the difference between timeObj and a struct_time object you can create for the epoch, create a datetime.datetime object. Example:
Expand|Select|Wrap|Line Numbers
  1. dt1 = datetime.datetime(*timeObj[:6])
The difference is:
Expand|Select|Wrap|Line Numbers
  1. td1 = dt1-dt2
The seconds to the epoch is then:
Expand|Select|Wrap|Line Numbers
  1. td1.total_seconds()
To adjust for local time:
Expand|Select|Wrap|Line Numbers
  1. td1.total_seconds()+time.timezone
To convert back to a string representation:
Expand|Select|Wrap|Line Numbers
  1. time.strftime("%d.%m.%Y %H:%M:%S", timeObj)

Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
This can be done with the time and datetime modules. Use time.strptime to create struct_time objects. Example:
Expand|Select|Wrap|Line Numbers
  1. timeObj = time.strptime(data, "%d.%m.%Y %H:%M:%S")
To determine the difference between timeObj and a struct_time object you can create for the epoch, create a datetime.datetime object. Example:
Expand|Select|Wrap|Line Numbers
  1. dt1 = datetime.datetime(*timeObj[:6])
The difference is:
Expand|Select|Wrap|Line Numbers
  1. td1 = dt1-dt2
The seconds to the epoch is then:
Expand|Select|Wrap|Line Numbers
  1. td1.total_seconds()
To adjust for local time:
Expand|Select|Wrap|Line Numbers
  1. td1.total_seconds()+time.timezone
To convert back to a string representation:
Expand|Select|Wrap|Line Numbers
  1. time.strftime("%d.%m.%Y %H:%M:%S", timeObj)
Jan 24 '14 #2

Post your reply

Sign in to post your reply or Sign up for a free account.