Convert Datetime To Timestamp in Python
What is Timestamp
The unix time stamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC.
It should also be pointed out that this point in time technically does not change no matter where you are located on the globe.
Convert String date to Timestamp
1 | from __future__ import division |
WRONG VERSIONtime
module is for time access and conversions.datetime
module is for basic date and time types.
1 | import time |
datetime.strptime()
return a datetime
parsed accroding to format
..utctimetuple()
complete time obj with full 9-tuple, default adding numbers as 0
, equivalent to time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))
time.mktime()
takes argument as full 9-tuple time obj, and returns a floating point number.
mktime()
may return a wrong result ifd
corresponds to an ambiguous local time (e.g., during DST transition) or ifd
is a past(future) date when the utc offset might have been different and the Cmktime()
has no access to the tz database on the given platform.
Python Timezone
pytz
module can be used for time localization, date arithmetic and etc.pytz.country_timezones('country code')
could return a list of time zone names. We can new a tzinfo
with pytz.timezone('time zone name')
.
1 | 'cn') timeZone = pytz.country_timezones( |
The wired thing is, there’s always a time offset between any Chinese local times and Beijing local time. But when it comes to Taipei local time, it’s the same with Beijing local time. Then we can use Taipei time as a alternative.
Local time 2 UTC time
UTCtime = Localtime - timezone
E.g. Beijing local time 18:00, UTCtime = 18:00 - (+ 08:00) = 10:00 + 00:00, so UTC time is 10:00.
1 |
|
Reference
[1] Epoch Unix Time Stamp Converter
[2] StackOverFlow: Convert string date to timestamp in Python
[3] 用datetime和pytz来转换时区
[4] StackOverFlow: Converting datetime.date to UTC timestamp in Python