How to specify time zone (UTC) when converting to Unix time? (Python) - python

I have a utc timestamp in the IS8601 format and am trying to convert it to unix time. This is my console session:
In [9]: mydate
Out[9]: '2009-07-17T01:21:00.000Z'
In [10]: parseddate = iso8601.parse_date(mydate)
In [14]: ti = time.mktime(parseddate.timetuple())
In [25]: datetime.datetime.utcfromtimestamp(ti)
Out[25]: datetime.datetime(2009, 7, 17, 7, 21)
In [26]: datetime.datetime.fromtimestamp(ti)
Out[26]: datetime.datetime(2009, 7, 17, 2, 21)
In [27]: ti
Out[27]: 1247815260.0
In [28]: parseddate
Out[28]: datetime.datetime(2009, 7, 17, 1, 21, tzinfo=<iso8601.iso8601.Utc object at 0x01D74C70>)
As you can see, I can't get the correct time back. The hour is ahead by one if i use fromtimestamp(), and it's ahead by six hours if i use utcfromtimestamp()
Any advice?
Thanks!

You can create an struct_time in UTC with datetime.utctimetuple() and then convert this to a unix timestamp with calendar.timegm():
calendar.timegm(parseddate.utctimetuple())
This also takes care of any daylight savings time offset, because utctimetuple() normalizes this.

I am just guessing, but one hour difference can be not because of time zones, but because of daylight savings on/off.

naive_utc_dt = parseddate.replace(tzinfo=None)
timestamp = (naive_utc_dt - datetime(1970, 1, 1)).total_seconds()
# -> 1247793660.0
See more details in another answer to similar question.
And back:
utc_dt = datetime.utcfromtimestamp(timestamp)
# -> datetime.datetime(2009, 7, 17, 1, 21)

import time
import datetime
import calendar
def date_time_to_utc_epoch(dt_utc): #convert from utc date time object (yyyy-mm-dd hh:mm:ss) to UTC epoch
frmt="%Y-%m-%d %H:%M:%S"
dtst=dt_utc.strftime(frmt) #convert datetime object to string
time_struct = time.strptime(dtst, frmt) #convert time (yyyy-mm-dd hh:mm:ss) to time tuple
epoch_utc=calendar.timegm(time_struct) #convert time to to epoch
return epoch_utc
#----test function --------
now_datetime_utc = int(date_time_to_utc_epoch(datetime.datetime.utcnow()))
now_time_utc = int(time.time())
print (now_datetime_utc)
print (now_time_utc)
if now_datetime_utc == now_time_utc :
print ("Passed")
else :
print("Failed")

Related

In python convert seconds from 1970 to hours since 1900

Have two data sets with different time format. One in epcoh time, seconds from 1/1/1970, and the other hours since 1/1/1900. Need to convert the first to the second one. How can I do that in python ?
Thanks
So, for starters, here are the necessary tools:
from datetime import datetime, timezone, timedelta
Then you need to establish the starting time:
atmos_epoch = datetime(1900, 1, 1, 0, 0, tzinfo=timezone.utc)
Then you can work with deltas to that time:
>>> d = datetime.now(timezone.utc) - atmos_epoch
>>> d
datetime.timedelta(days=43893, seconds=28215, microseconds=982930)
>>> d.total_seconds() / 60 / 60
1053439.8377730362
That last value is the difference in hours.
You can add deltas to that epoch timestamp:
>>> atmos_epoch + timedelta(hours=1000000)
datetime.datetime(2014, 1, 29, 16, 0, tzinfo=datetime.timezone.utc)
The other thing you talk about, seconds since 1970, are simply UNIX timestamps, which you can work with easily:
>>> datetime.now().timestamp()
1583395060.91666
>>> datetime.fromtimestamp(1500000000)
datetime.datetime(2017, 7, 14, 4, 40)
Now you have a way to convert from both values to datetime objects and from datetime objects to either value.

Get file modification date in MM-DD-YYYY format without time [duplicate]

I have a date string and want to convert it to the date type:
I have tried to use datetime.datetime.strptime with the format that I want but it is returning the time with the conversion.
when = alldates[int(daypos[0])]
print when, type(when)
then = datetime.datetime.strptime(when, '%Y-%m-%d')
print then, type(then)
This is what the output returns:
2013-05-07 <type 'str'>
2013-05-07 00:00:00 <type 'datetime.datetime'>
I need to remove the time: 00:00:00.
print then.date()
What you want is a datetime.date object. What you have is a datetime.datetime object. You can either change the object when you print as per above, or do the following when creating the object:
then = datetime.datetime.strptime(when, '%Y-%m-%d').date()
If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do
>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)
Note that this returns a new datetime object -- now remains unchanged.
>>> print then.date(), type(then.date())
2013-05-07 <type 'datetime.date'>
To convert a string into a date, the easiest way AFAIK is the dateutil module:
import dateutil.parser
datetime_object = dateutil.parser.parse("2013-05-07")
It can also handle time zones:
print(dateutil.parser.parse("2013-05-07"))
>>> datetime.datetime(2013, 5, 7, 1, 12, 12, tzinfo=tzutc())
If you have a datetime object, say:
import pytz
import datetime
now = datetime.datetime.now(pytz.UTC)
and you want chop off the time part, then I think it is easier to construct a new object instead of "substracting the time part". It is shorter and more bullet proof:
date_part datetime.datetime(now.year, now.month, now.day, tzinfo=now.tzinfo)
It also keeps the time zone information, it is easier to read and understand than a timedelta substraction, and you also have the option to give a different time zone in the same step (which makes sense, since you will have zero time part anyway).
For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:
date = datetime.datetime.utcnow()
start_of_day = date - datetime.timedelta(
hours=date.hour,
minutes=date.minute,
seconds=date.second,
microseconds=date.microsecond
)
end_of_day = start_of_day + datetime.timedelta(
hours=23,
minutes=59,
seconds=59
)
Example output:
>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)
If you specifically want a datetime and not a date but want the time zero'd out you could combine date with datetime.min.time()
Example:
datetime.datetime.combine(datetime.datetime.today().date(),
datetime.datetime.min.time())
You can use simply pd.to_datetime(then) and pandas will convert the date elements into ISO date format- [YYYY-MM-DD].
You can pass this as map/apply to use it in a dataframe/series too.
You can usee the following code:
week_start = str(datetime.today() - timedelta(days=datetime.today().weekday() % 7)).split(' ')[0]

Python: Convert UTC time to localtime given UTC offset

Given the following Python datetime object representing an UTC time:
2016-09-15 22:13:03-2:00
I'm trying to obtain the corresponding local time datetime, where the UTC offset is applied:
2016-09-15 20:13:03
I was hoping to find a method in the datetime module that was able to do this, but I did not succeed. Any help is very appreciated.
Regards
I do not know if this is the best answer but here is what I have for you. Typically I would not do this since it is better to use the UTC time and convert
Here is a example:
value = datetime.datetime.strptime(str(utc_datetime), '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc)
value = value.astimezone(pytz.timezone("America/Los_Angeles"))
I was unable to use your datetime as the syntax is a bit off so I went ahead and used dateutil.parser to convert it to a datetime object
>>> from dateutil.parser import parse
>>> val = parse('2016-09-15 22:13:03-2:00')
There are other ways to set a datetime object to UTC but I find pytz to be the easiest
>>> import pytz
>>> utc_val = val.replace(tzinfo=pytz.utc)
Here is the output of those two values. From here I grab the delta and subtract it
>>> val, utc_val
(datetime.datetime(2016, 9, 15, 22, 13, 3, tzinfo=tzoffset(None, -7200)), datetime.datetime(2016, 9, 15, 22, 13, 3, tzinfo=<UTC>))
>>>
>>> delta = val - utc_val
I remove the tzinfo since this is a converted datetime value
>>> local_dt = (val - delta).replace(tzinfo=None)
>>> local_dt
datetime.datetime(2016, 9, 15, 20, 13, 3)
>>> str(local_dt)
'2016-09-15 20:13:03'

Substract current time to -GMT in python

I have a time which is 13:11:06 and i want to -GMT (i.e -0530). I can minus it by simply doing -5 by splitting the string taking the first digit (convert to int) and then minus it and then re-join. But then i get it in a format which is 8:11:06 which is not right as it should be 08:11:06, secondly its a lengthy process. Is there a easy way to get my time in -GMT format (08:11:06)
This is what i did to get -GMT time after getting the datetime
timesplithour = int(timesplit[1]) + -5
timesplitminute = timesplit[2]
timesplitseconds = timesplit[3]
print timesplithour
print timesplitminute
print timesplitseconds
print timesplithour + ":" + timesplitminute + ":" + timesplitseconds
You could use Python's datatime library to help you as follows:
import datetime
my_time = "13:11:06"
new_time = datetime.datetime.strptime("2016 " + my_time, "%Y %H:%M:%S") - datetime.timedelta(hours=5, minutes=30)
print new_time.strftime("%H:%M:%S")
This would print:
07:41:06
First it converts your string into a datetime object. It then creates a timedelta object allowing you to subtract 5 hours 30 minutes from the datetime object. Finally it uses strftime to format the resulting datetime into a string in the same format.
Use the datetime module:
from datetime import datetime, timedelta
dt = datetime.strptime('13:11:06', '%H:%M:%S')
time_gmt = (dt - timedelta(hours=5, minutes=30)).time()
print(time_gmt.hour)
print(time_gmt.minute)
print(time_gmt.second)
s = time_gmt.strftime('%H:%M:%S')
print(s)
Output
7
41
6
07:41:06
Note that this subtracts 5 hours and 30 minutes as initially mentioned in the question. If you really only want to subtract 5 hours, use timedelta(hours=5).
You can use datetimes timedelta.
print datetime.datetime.today()
>>> datetime.datetime(2016, 3, 3, 10, 45, 6, 270711)
print datetime.datetime.today() - datetime.timedelta(days=3)
>>> datetime.datetime(2016, 2, 29, 10, 45, 8, 559073)
This way you can subtract easily
Assuming the time is a datetime instance
import datetime as dt
t = datetime(2015,12,31,13,11,06)
#t.time() # gives time object. ie no date information
offset = dt.timedelta(hours=5,minutes=30) # or hours=5.5
t -= offset
t.strftime(("%H:%M:%S") # output as your desired string
#'18:41:06'
If the object is datetime and you don't care about DST, the simplest thing you can do is,
In [1]: from datetime import datetime
In [2]: curr = datetime.now()
In [3]: curr
Out[3]: datetime.datetime(2016, 3, 3, 9, 57, 31, 302231)
In [4]: curr.utcnow()
Out[4]: datetime.datetime(2016, 3, 3, 8, 57, 57, 286956)

Convert the unicode to datetime format

A function returns date and time in unicode format.
u'2014-03-06T04:38:51Z'
I wish to convert this to date and time format and subtract it with current datetime to get the number of days in between.
Thanks in advance
Check string is unicode
>>> import types
>>> type(u'2014-03-06T04:38:51Z') is types.UnicodeType
True
Converting strings to datetime:
>>> import datetime
>>> datetime.datetime.strptime(u'2014-03-06T04:38:51Z', '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2014, 3, 6, 4, 38, 51)
Subtract from today to
>>> import datetime
>>> today = datetime.datetime.today()
>>> yourdate = datetime.datetime.strptime(u'2014-03-06T04:38:51Z', '%Y-%m-%dT%H:%M:%SZ')
>>> difference = today - yourdate
print str(difference)
First you have to convert your string to a datetime.datetime object.
import datetime
then = datetime.datetime.strptime(u'2014-03-06T04:38:51Z', "%Y-%m-%dT%H:%M:%SZ")
then represents itself as datetime.datetime(2014, 3, 6, 4, 38, 51), which looks about right. Then you have to get today's date as a datetime.datetime.
now = datetime.datetime.now()
Finally subtract it from your date (or vice versa - the question didn't make it clear).delta is a datetime.timedelta object that stores increments in days, seconds and microseconds. The latter two are always positive, the first can be negative.
for delta in (now-then, then-now):
print(delta, "::", delta.days, delta.seconds, delta.microseconds)
This prints out:
-1 day, 20:18:14.250142 :: -1 73094 250142
3:41:45.749858 :: 0 13305 749858
Best try it with a few examples to convince yourself it's correct.

Categories

Resources