Python's datetime conversion - python

Here's my code:
from datetime import datetime
def get_local_time(time_str):
"""
takes a string in the format of '27 March at 3:00' which is UTC
and converts it to local time and AM/PM
:param time_str:
"""
offset = datetime.now() - datetime.utcnow()
time_dt = datetime.strptime(time_str, '%d %b at %H:%M')
return (time_dt + offset).strftime('%I:%M %p')
What I'm having problems with is using a time_str that's only the time and doesn't include the day/month. ie: "02:00"
If I change it to: time_dt = datetime.strptime(time_str, '%H:%M') then I get an error about strftime and years before 1900.
So I'm stumped here. What needs done to allow just a time in the input string?

You can try with dateutil package. The parser.parse() method is good when your input string changes. It will construct a datetime object with todays date if only time is specified in the string. It will handle various other formats.
from datetime import datetime
from dateutil import parser
def get_local_time(time_str):
"""
takes a string in the format of '27 March at 3:00' which is UTC
and converts it to local time and AM/PM
:param time_str:
"""
offset = datetime.now() - datetime.utcnow()
time_dt = parser.parse(time_str)
return (time_dt + offset).strftime('%I:%M %p')
If you are restricted to only datetime package you can do something like this:
from datetime import datetime
def get_local_time(time_str):
"""
takes a string in the format of '27 March at 3:00' which is UTC
and converts it to local time and AM/PM
:param time_str:
"""
if len(time_str) <= 5:
time_str = datetime.now().strftime('%d %B at ') + time_str
offset = datetime.now() - datetime.utcnow()
time_dt = datetime.strptime(time_str, '%d %B at %H:%M')
return (time_dt + offset).strftime('%I:%M %p')
print get_local_time('27 March at 3:00')
print get_local_time('3:00')
Or you can do it like so:
from datetime import datetime
def get_local_time(time_str):
"""
takes a string in the format of '27 March at 3:00' which is UTC
and converts it to local time and AM/PM
:param time_str:
"""
offset = datetime.now() - datetime.utcnow()
if len(time_str) <= 5:
time_dt = datetime.combine(datetime.now().date(), datetime.strptime(time_str, '%H:%M').time())
else:
time_dt = datetime.strptime(time_str, '%d %B at %H:%M')
return (time_dt + offset).strftime('%I:%M %p')
print get_local_time('27 March at 3:00')
print get_local_time('3:00')

I just tried it in the repl. It worked for me:
>>> from datetime import datetime
>>> time = "02:00"
>>> time_dt = datetime.strptime(time, '%H:%M')
>>> time_dt
datetime.datetime(1900, 1, 1, 2, 0)
>>>
If I remember right, a datetime can never store just a time, there will always be a dummy date of January 1, 1900. If you want to store the time without the dummy date, try using the time class. It also has a strftime function, see the docs here: https://docs.python.org/2/library/time.html
You could also try adding a different dummy date to your datetime if it isn't working.

Related

facing difficulties converting utc timezone to local

I am getting date and time like this
date_time = "2022-02-17 08:29:36.345374"
And to convert these to AM, PM format I am doing something like this
date_formate = datetime.fromisoformat(date_time).strftime('%d/%m/%Y %I:%M %p')
but End time I am getting is in not local time seems it's in UTC , I am trying to convert it in utc but no luck doing something like this
dtUTC = datetime.fromisoformat(date_formate[:-1])
dtZone = dtUTC.astimezone()
print(dtZone.isoformat(timespec='seconds'))
got this solution on stackoverflow but getting error Invalid isoformat string: '2022-02-17 08:29:36.345374'
Python assumes local time by default if you don't specify a time zone / UTC offset. So in this case, you need to set UTC first, then convert, then format (if you want a string as output):
from datetime import datetime, timezone
date_time = "2022-02-17 08:29:36.345374" # UTC is not specified here...
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone()
print(local) # my tz was on UTC+1 at that date...
# 2022-02-17 09:29:36.345374+01:00
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 09:29 AM
If astimezone(None) does not work, you can try tzlocal;
import tzlocal
zone = tzlocal.get_localzone()
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone(zone)
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 09:29 AM
or derive a timezone object from a timedelta, e.g.
from datetime import timedelta
zone = timezone(timedelta(minutes=-300)) # UTC-5 hours
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone(zone)
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 03:29 AM

Subtract datetime in python, understanding formats

Given I have a timestamp:
date_time_str = '2019-09-10T13:48:06+0200'
How can I calculate the time difference between the current time and this datetime?
I've got it so far with an impression of strong wrongdoing - this should be possible in a far simpler way:
from datetime import datetime, timezone
import time
date_time_str = '2019-09-10T13:48:06+0200'
format = '%Y-%m-%dT%H:%M:%S%z'
date_time_obj = datetime.strptime(date_time_str, format)
now = datetime.now()
now_time = now.strftime(format)
print(now_time)
now=datetime.strptime(datetime.fromtimestamp(int(time.time()), tz=timezone.utc).isoformat(), format)
print("now is: %s" % now)
print(now-time_obj)
The above program does not work because the current time comes out in a slightly different formatting:
'2019-09-10T15:56:11+00:00'
That is, if you run the above script for example Python 3.6.5, you get the error:
ValueError: time data '2019-09-10T18:18:09+00:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
The mismatch is in the timezone format, "+00:00" vs. "+0200".
You can use datetime.now() to get the current datetime in utc:
# Same as your code
from datetime import datetime, timezone
date_time_str = '2019-09-10T13:48:06+0200'
format = '%Y-%m-%dT%H:%M:%S%z'
date_time_obj = datetime.strptime(date_time_str, format)
# Added:
print(datetime.now(tz=timezone.utc))
# 2019-09-10 18:35:48.066548+00:00
print(datetime.now(tz=timezone.utc) - date_time_obj)
# 6:47:42.066548

How to fix date formatting using python3

I have data with the date format as follows:
date_format = 190410
year = 19
month = 04
date = 10
I want to change the date format, to be like this:
date_format = 10-04-2019
How do I solve this problem?
>>> import datetime
>>> date = 190410
>>> datetime.datetime.strptime(str(date), "%y%m%d").strftime("%d-%m-%Y")
'10-04-2019'
datetime.strptime() takes a data string and a format, and turns that into datetime object, and datetime objects have a method called strftime that turns datetime objects to string with given format. You can look what %y %m %d %Y are from here.
This is what you want(Notice that you have to change your format)
import datetime
date_format = '2019-04-10'
date_time_obj = datetime.datetime.strptime(date_format, '%Y-%m-%d')
print(date_time_obj)
Here is an other example
import datetime
date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)
You can also do this
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
print(date)
There are many ways to achieve what you want.

Why am I gaining an hour when converting to/from epoch timestamp? [duplicate]

I am dealing with dates in Python and I need to convert them to UTC timestamps to be used
inside Javascript. The following code does not work:
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datetime(2010, 12, 31, 23, 0)
Converting the date object first to datetime also does not help. I tried the example at this link from, but:
from pytz import utc, timezone
from datetime import datetime
from time import mktime
input_date = datetime(year=2011, month=1, day=15)
and now either:
mktime(utc.localize(input_date).utctimetuple())
or
mktime(timezone('US/Eastern').localize(input_date).utctimetuple())
does work.
So general question: how can I get a date converted to seconds since epoch according to UTC?
If d = date(2011, 1, 1) is in UTC:
>>> from datetime import datetime, date
>>> import calendar
>>> timestamp1 = calendar.timegm(d.timetuple())
>>> datetime.utcfromtimestamp(timestamp1)
datetime.datetime(2011, 1, 1, 0, 0)
If d is in local timezone:
>>> import time
>>> timestamp2 = time.mktime(d.timetuple()) # DO NOT USE IT WITH UTC DATE
>>> datetime.fromtimestamp(timestamp2)
datetime.datetime(2011, 1, 1, 0, 0)
timestamp1 and timestamp2 may differ if midnight in the local timezone is not the same time instance as midnight in UTC.
mktime() may return a wrong result if d corresponds to an ambiguous local time (e.g., during DST transition) or if d is a past(future) date when the utc offset might have been different and the C mktime() has no access to the tz database on the given platform. You could use pytz module (e.g., via tzlocal.get_localzone()) to get access to the tz database on all platforms. Also, utcfromtimestamp() may fail and mktime() may return non-POSIX timestamp if "right" timezone is used.
To convert datetime.date object that represents date in UTC without calendar.timegm():
DAY = 24*60*60 # POSIX day in seconds (exact value)
timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * DAY
timestamp = (utc_date - date(1970, 1, 1)).days * DAY
How can I get a date converted to seconds since epoch according to UTC?
To convert datetime.datetime (not datetime.date) object that already represents time in UTC to the corresponding POSIX timestamp (a float).
Python 3.3+
datetime.timestamp():
from datetime import timezone
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
Note: It is necessary to supply timezone.utc explicitly otherwise .timestamp() assume that your naive datetime object is in local timezone.
Python 3 (< 3.3)
From the docs for datetime.utcfromtimestamp():
There is no method to obtain the timestamp from a datetime instance,
but POSIX timestamp corresponding to a datetime instance dt can be
easily calculated as follows. For a naive dt:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
And for an aware dt:
timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1)
Interesting read: Epoch time vs. time of day on the difference between What time is it? and How many seconds have elapsed?
See also: datetime needs an "epoch" method
Python 2
To adapt the above code for Python 2:
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
where timedelta.total_seconds() is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled.
Example
from __future__ import division
from datetime import datetime, timedelta
def totimestamp(dt, epoch=datetime(1970,1,1)):
td = dt - epoch
# return td.total_seconds()
return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6
now = datetime.utcnow()
print now
print totimestamp(now)
Beware of floating-point issues.
Output
2012-01-08 15:34:10.022403
1326036850.02
How to convert an aware datetime object to POSIX timestamp
assert dt.tzinfo is not None and dt.utcoffset() is not None
timestamp = dt.timestamp() # Python 3.3+
On Python 3:
from datetime import datetime, timedelta, timezone
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
timestamp = (dt - epoch) / timedelta(seconds=1)
integer_timestamp = (dt - epoch) // timedelta(seconds=1)
On Python 2:
# utc time = local time - utc offset
utc_naive = dt.replace(tzinfo=None) - dt.utcoffset()
timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds()
For unix systems only:
>>> import datetime
>>> d = datetime.date(2011, 1, 1)
>>> d.strftime("%s") # <-- THIS IS THE CODE YOU WANT
'1293832800'
Note 1: dizzyf observed that this applies localized timezones. Don't use in production.
Note 2: Jakub Narębski noted that this ignores timezone information even for offset-aware datetime (tested for Python 2.7).
Assumption 1: You're attempting to convert a date to a timestamp, however since a date covers a 24 hour period, there isn't a single timestamp that represents that date. I'll assume that you want to represent the timestamp of that date at midnight (00:00:00.000).
Assumption 2: The date you present is not associated with a particular time zone, however you want to determine the offset from a particular time zone (UTC). Without knowing the time zone the date is in, it isn't possible to calculate a timestamp for a specific time zone. I'll assume that you want to treat the date as if it is in the local system time zone.
First, you can convert the date instance into a tuple representing the various time components using the timetuple() member:
dtt = d.timetuple() # time.struct_time(tm_year=2011, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)
You can then convert that into a timestamp using time.mktime:
ts = time.mktime(dtt) # 1293868800.0
You can verify this method by testing it with the epoch time itself (1970-01-01), in which case the function should return the timezone offset for the local time zone on that date:
d = datetime.date(1970,1,1)
dtt = d.timetuple() # time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=-1)
ts = time.mktime(dtt) # 28800.0
28800.0 is 8 hours, which would be correct for the Pacific time zone (where I'm at).
I defined my own two functions
utc_time2datetime(utc_time, tz=None)
datetime2utc_time(datetime)
here:
import time
import datetime
from pytz import timezone
import calendar
import pytz
def utc_time2datetime(utc_time, tz=None):
# convert utc time to utc datetime
utc_datetime = datetime.datetime.fromtimestamp(utc_time)
# add time zone to utc datetime
if tz is None:
tz_datetime = utc_datetime.astimezone(timezone('utc'))
else:
tz_datetime = utc_datetime.astimezone(tz)
return tz_datetime
def datetime2utc_time(datetime):
# add utc time zone if no time zone is set
if datetime.tzinfo is None:
datetime = datetime.replace(tzinfo=timezone('utc'))
# convert to utc time zone from whatever time zone the datetime is set to
utc_datetime = datetime.astimezone(timezone('utc')).replace(tzinfo=None)
# create a time tuple from datetime
utc_timetuple = utc_datetime.timetuple()
# create a time element from the tuple an add microseconds
utc_time = calendar.timegm(utc_timetuple) + datetime.microsecond / 1E6
return utc_time
follow the python2.7 document, you have to use calendar.timegm() instead of time.mktime()
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(calendar.timegm(d.timetuple()))
datetime.datetime(2011, 1, 1, 0, 0)
A complete time-string contains:
date
time
utcoffset [+HHMM or -HHMM]
For example:
1970-01-01 06:00:00 +0500 == 1970-01-01 01:00:00 +0000 == UNIX timestamp:3600
$ python3
>>> from datetime import datetime
>>> from calendar import timegm
>>> tm = '1970-01-01 06:00:00 +0500'
>>> fmt = '%Y-%m-%d %H:%M:%S %z'
>>> timegm(datetime.strptime(tm, fmt).utctimetuple())
3600
Note:
UNIX timestamp is a floating point number expressed in seconds since the epoch, in UTC.
Edit:
$ python3
>>> from datetime import datetime, timezone, timedelta
>>> from calendar import timegm
>>> dt = datetime(1970, 1, 1, 6, 0)
>>> tz = timezone(timedelta(hours=5))
>>> timegm(dt.replace(tzinfo=tz).utctimetuple())
3600
Using the arrow package:
>>> import arrow
>>> arrow.get(2010, 12, 31).timestamp
1293753600
>>> time.gmtime(1293753600)
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31,
tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=4, tm_yday=365, tm_isdst=0)
the question is a little confused. timestamps are not UTC - they're a Unix thing. the date might be UTC? assuming it is, and if you're using Python 3.2+, simple-date makes this trivial:
>>> SimpleDate(date(2011,1,1), tz='utc').timestamp
1293840000.0
if you actually have the year, month and day you don't need to create the date:
>>> SimpleDate(2011,1,1, tz='utc').timestamp
1293840000.0
and if the date is in some other timezone (this matters because we're assuming midnight without an associated time):
>>> SimpleDate(date(2011,1,1), tz='America/New_York').timestamp
1293858000.0
[the idea behind simple-date is to collect all python's date and time stuff in one consistent class, so you can do any conversion. so, for example, it will also go the other way:
>>> SimpleDate(1293858000, tz='utc').date
datetime.date(2011, 1, 1)
]
Considering you have a datetime object called d,
use the following to get the timestamp in UTC:
d.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
And for the opposite direction, use following :
d = datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")
This works for me, pass through a function.
from datetime import timezone, datetime, timedelta
import datetime
def utc_converter(dt):
dt = datetime.datetime.now(timezone.utc)
utc_time = dt.replace(tzinfo=timezone.utc)
utc_timestamp = utc_time.timestamp()
return utc_timestamp
# create start and end timestamps
_now = datetime.datetime.now()
str_start = str(utc_converter(_now))
_end = _now + timedelta(seconds=10)
str_end = str(utc_converter(_end))
i'm impressed of the deep discussion.
my 2 cents:
from datetime import datetime
import time
the timestamp in utc is:
timestamp = \
(datetime.utcnow() - datetime(1970,1,1)).total_seconds()
or,
timestamp = time.time()
if now results from datetime.now(), in the same DST
utcoffset = (datetime.now() - datetime.utcnow()).total_seconds()
timestamp = \
(now - datetime(1970,1,1)).total_seconds() - utcoffset

Converting datetime.date to UTC timestamp in Python

I am dealing with dates in Python and I need to convert them to UTC timestamps to be used
inside Javascript. The following code does not work:
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datetime(2010, 12, 31, 23, 0)
Converting the date object first to datetime also does not help. I tried the example at this link from, but:
from pytz import utc, timezone
from datetime import datetime
from time import mktime
input_date = datetime(year=2011, month=1, day=15)
and now either:
mktime(utc.localize(input_date).utctimetuple())
or
mktime(timezone('US/Eastern').localize(input_date).utctimetuple())
does work.
So general question: how can I get a date converted to seconds since epoch according to UTC?
If d = date(2011, 1, 1) is in UTC:
>>> from datetime import datetime, date
>>> import calendar
>>> timestamp1 = calendar.timegm(d.timetuple())
>>> datetime.utcfromtimestamp(timestamp1)
datetime.datetime(2011, 1, 1, 0, 0)
If d is in local timezone:
>>> import time
>>> timestamp2 = time.mktime(d.timetuple()) # DO NOT USE IT WITH UTC DATE
>>> datetime.fromtimestamp(timestamp2)
datetime.datetime(2011, 1, 1, 0, 0)
timestamp1 and timestamp2 may differ if midnight in the local timezone is not the same time instance as midnight in UTC.
mktime() may return a wrong result if d corresponds to an ambiguous local time (e.g., during DST transition) or if d is a past(future) date when the utc offset might have been different and the C mktime() has no access to the tz database on the given platform. You could use pytz module (e.g., via tzlocal.get_localzone()) to get access to the tz database on all platforms. Also, utcfromtimestamp() may fail and mktime() may return non-POSIX timestamp if "right" timezone is used.
To convert datetime.date object that represents date in UTC without calendar.timegm():
DAY = 24*60*60 # POSIX day in seconds (exact value)
timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * DAY
timestamp = (utc_date - date(1970, 1, 1)).days * DAY
How can I get a date converted to seconds since epoch according to UTC?
To convert datetime.datetime (not datetime.date) object that already represents time in UTC to the corresponding POSIX timestamp (a float).
Python 3.3+
datetime.timestamp():
from datetime import timezone
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
Note: It is necessary to supply timezone.utc explicitly otherwise .timestamp() assume that your naive datetime object is in local timezone.
Python 3 (< 3.3)
From the docs for datetime.utcfromtimestamp():
There is no method to obtain the timestamp from a datetime instance,
but POSIX timestamp corresponding to a datetime instance dt can be
easily calculated as follows. For a naive dt:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
And for an aware dt:
timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1)
Interesting read: Epoch time vs. time of day on the difference between What time is it? and How many seconds have elapsed?
See also: datetime needs an "epoch" method
Python 2
To adapt the above code for Python 2:
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
where timedelta.total_seconds() is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled.
Example
from __future__ import division
from datetime import datetime, timedelta
def totimestamp(dt, epoch=datetime(1970,1,1)):
td = dt - epoch
# return td.total_seconds()
return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6
now = datetime.utcnow()
print now
print totimestamp(now)
Beware of floating-point issues.
Output
2012-01-08 15:34:10.022403
1326036850.02
How to convert an aware datetime object to POSIX timestamp
assert dt.tzinfo is not None and dt.utcoffset() is not None
timestamp = dt.timestamp() # Python 3.3+
On Python 3:
from datetime import datetime, timedelta, timezone
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
timestamp = (dt - epoch) / timedelta(seconds=1)
integer_timestamp = (dt - epoch) // timedelta(seconds=1)
On Python 2:
# utc time = local time - utc offset
utc_naive = dt.replace(tzinfo=None) - dt.utcoffset()
timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds()
For unix systems only:
>>> import datetime
>>> d = datetime.date(2011, 1, 1)
>>> d.strftime("%s") # <-- THIS IS THE CODE YOU WANT
'1293832800'
Note 1: dizzyf observed that this applies localized timezones. Don't use in production.
Note 2: Jakub Narębski noted that this ignores timezone information even for offset-aware datetime (tested for Python 2.7).
Assumption 1: You're attempting to convert a date to a timestamp, however since a date covers a 24 hour period, there isn't a single timestamp that represents that date. I'll assume that you want to represent the timestamp of that date at midnight (00:00:00.000).
Assumption 2: The date you present is not associated with a particular time zone, however you want to determine the offset from a particular time zone (UTC). Without knowing the time zone the date is in, it isn't possible to calculate a timestamp for a specific time zone. I'll assume that you want to treat the date as if it is in the local system time zone.
First, you can convert the date instance into a tuple representing the various time components using the timetuple() member:
dtt = d.timetuple() # time.struct_time(tm_year=2011, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)
You can then convert that into a timestamp using time.mktime:
ts = time.mktime(dtt) # 1293868800.0
You can verify this method by testing it with the epoch time itself (1970-01-01), in which case the function should return the timezone offset for the local time zone on that date:
d = datetime.date(1970,1,1)
dtt = d.timetuple() # time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=-1)
ts = time.mktime(dtt) # 28800.0
28800.0 is 8 hours, which would be correct for the Pacific time zone (where I'm at).
I defined my own two functions
utc_time2datetime(utc_time, tz=None)
datetime2utc_time(datetime)
here:
import time
import datetime
from pytz import timezone
import calendar
import pytz
def utc_time2datetime(utc_time, tz=None):
# convert utc time to utc datetime
utc_datetime = datetime.datetime.fromtimestamp(utc_time)
# add time zone to utc datetime
if tz is None:
tz_datetime = utc_datetime.astimezone(timezone('utc'))
else:
tz_datetime = utc_datetime.astimezone(tz)
return tz_datetime
def datetime2utc_time(datetime):
# add utc time zone if no time zone is set
if datetime.tzinfo is None:
datetime = datetime.replace(tzinfo=timezone('utc'))
# convert to utc time zone from whatever time zone the datetime is set to
utc_datetime = datetime.astimezone(timezone('utc')).replace(tzinfo=None)
# create a time tuple from datetime
utc_timetuple = utc_datetime.timetuple()
# create a time element from the tuple an add microseconds
utc_time = calendar.timegm(utc_timetuple) + datetime.microsecond / 1E6
return utc_time
follow the python2.7 document, you have to use calendar.timegm() instead of time.mktime()
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(calendar.timegm(d.timetuple()))
datetime.datetime(2011, 1, 1, 0, 0)
A complete time-string contains:
date
time
utcoffset [+HHMM or -HHMM]
For example:
1970-01-01 06:00:00 +0500 == 1970-01-01 01:00:00 +0000 == UNIX timestamp:3600
$ python3
>>> from datetime import datetime
>>> from calendar import timegm
>>> tm = '1970-01-01 06:00:00 +0500'
>>> fmt = '%Y-%m-%d %H:%M:%S %z'
>>> timegm(datetime.strptime(tm, fmt).utctimetuple())
3600
Note:
UNIX timestamp is a floating point number expressed in seconds since the epoch, in UTC.
Edit:
$ python3
>>> from datetime import datetime, timezone, timedelta
>>> from calendar import timegm
>>> dt = datetime(1970, 1, 1, 6, 0)
>>> tz = timezone(timedelta(hours=5))
>>> timegm(dt.replace(tzinfo=tz).utctimetuple())
3600
Using the arrow package:
>>> import arrow
>>> arrow.get(2010, 12, 31).timestamp
1293753600
>>> time.gmtime(1293753600)
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31,
tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=4, tm_yday=365, tm_isdst=0)
the question is a little confused. timestamps are not UTC - they're a Unix thing. the date might be UTC? assuming it is, and if you're using Python 3.2+, simple-date makes this trivial:
>>> SimpleDate(date(2011,1,1), tz='utc').timestamp
1293840000.0
if you actually have the year, month and day you don't need to create the date:
>>> SimpleDate(2011,1,1, tz='utc').timestamp
1293840000.0
and if the date is in some other timezone (this matters because we're assuming midnight without an associated time):
>>> SimpleDate(date(2011,1,1), tz='America/New_York').timestamp
1293858000.0
[the idea behind simple-date is to collect all python's date and time stuff in one consistent class, so you can do any conversion. so, for example, it will also go the other way:
>>> SimpleDate(1293858000, tz='utc').date
datetime.date(2011, 1, 1)
]
Considering you have a datetime object called d,
use the following to get the timestamp in UTC:
d.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
And for the opposite direction, use following :
d = datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")
This works for me, pass through a function.
from datetime import timezone, datetime, timedelta
import datetime
def utc_converter(dt):
dt = datetime.datetime.now(timezone.utc)
utc_time = dt.replace(tzinfo=timezone.utc)
utc_timestamp = utc_time.timestamp()
return utc_timestamp
# create start and end timestamps
_now = datetime.datetime.now()
str_start = str(utc_converter(_now))
_end = _now + timedelta(seconds=10)
str_end = str(utc_converter(_end))
i'm impressed of the deep discussion.
my 2 cents:
from datetime import datetime
import time
the timestamp in utc is:
timestamp = \
(datetime.utcnow() - datetime(1970,1,1)).total_seconds()
or,
timestamp = time.time()
if now results from datetime.now(), in the same DST
utcoffset = (datetime.now() - datetime.utcnow()).total_seconds()
timestamp = \
(now - datetime(1970,1,1)).total_seconds() - utcoffset

Categories

Resources