Python datetime.today() to handle timezone - python

Hi apologies on basic python datetime question but I am a little confused:
I want to just have a variable the prints today's date, with consideration to the time zone the program I am running it in. Let's say California.
import datetime
import pytz
utc_now = pytz.utc.localize(datetime.datetime.utcnow())
pst_now = utc_now.astimezone(pytz.timezone("America/Los_Angeles"))
x = pst_now.isoformat()
for x it returns :
2020-01-13T17:43:56.155556-08:00
how can I get it to return:
2020-01-13
I tried:
datetime.datetime.strptime(x, '%Y-%m-%d)
But it did not work

If you're just looking to return the time of the local machine, no need to deal with timezones directly in your code, you can use the now function of datetime.
import datetime
datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')

x is a string. pst_now is a datetime object which, when the method .isoformat() is called on it, produces a string.
Solution: call strftime on pst_now:
x = pst_now.strftime('%Y-%m-%d')

You can convert pst_now to a date() object:
pst_now.date().isoformat()
'2020-01-13'

Related

Python Faker Datetime Generation returns tuple with datetime in it - instead just datetime

for testing purposes i want to compare two datetime objects.
dt1 = fake.date_time() # assumming 2021-03-25 08:56:12
dt1 structure
dt2 = datetime.datetime.strptime('2021-03-25 08:56:12', "%Y-%m-%d %H:%M:%S")
dt2 structure
The comparision fails as i try to compare a datetime object with a tuple which has a datetime object in it.
If I try to just assign the first element of the tuple (dt1) like so:
dt1 = fake.date_time()[0]
I get the follow error:
Error directly assign tuple element
But if i do the following, it works:
dt1 = fake.date_time()
dt1 = dt1[0]
What do I not understand here? :( And why isn't faker directly returning a datetime?
Thank you for any help.
I use python 3.7 and faker 6.6.2.
As I was preparing the whole code to be passed here, I discovered the issue.
I copied this line from a dict definition, and it had the comma at the end...
dt = fake.date_time(),
Obviously then python creates a tuple, I just didn't see this.
If you check the Faker date_time function source code you'll see only a single datetime.datetime object retuns:
def date_time(self, tzinfo=None, end_datetime=None):
"""
Get a datetime object for a date between January 1, 1970 and now
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2005-08-16 20:39:21')
:return datetime
"""
# NOTE: On windows, the lowest value you can get from windows is 86400
# on the first day. Known python issue:
# https://bugs.python.org/issue30684
return datetime(1970, 1, 1, tzinfo=tzinfo) + \
timedelta(seconds=self.unix_time(end_datetime=end_datetime))
I suspect an unwanted change has been applied to the dt1 object (or it can be a debugger bug also), as I can see in the error clearly stated that the datetime.datetime object is not subscriptable . Would you add the complete code for further checking?

Datetime has no attribute datetime

I want to return datetime.datetime.strptime(date_visit,"%Y-%m-%d") into my function read_file but python keeps saying that datetime.datetime has no attribute datetime? In the function where I return it´s working. Pls help anyone.
return datetime.datetime.strptime(date_visit,"%Y-%m-%d")
def read_file(date):
all_animals = list()
day = datetime.datetime.strptime(date_visit,"%Y-%m-%d").isoweekday()
datetime.datetime.strptime(date_visit,"%Y-%m-%d")
workingday = [1,2,3,4,5]
Just replace import datetime.datetime by import datetime
Of course datetime.datetime does not have the attribute datetime. You should use it like this:
from datetime import datetime
datetime.strptime(...)
Or:
import datetime
datetime.datetime.strptime(...)
To use datetime.datetime.strptime() you need to import the whole module:
import datetime
The second datetime is a type in the first one, and it has strptime() function. For more details please check this link:
datetime — Basic date and time types

Converting datetime.time() intho the same format as time.time()

I'm using the following to get utc datetime:
import datetime
import time
from pytz import timezone
now_utc = datetime.datetime.now(timezone('UTC'))
now = time.time()
print now_utc.time(), now
>> 04:51:39.337515 1332823899.34
I need to convert the format of now_utc.time() to look like the output of time.time().
How do I do that? Or, how to I get time.time() in utc?
time.mktime(now_utc.timetuple())
Updating the answer, since it was completely wrong, but mistake I made can be useful for others.
time.mktime does not retain the timezone, using the tuple as a local time, so this:
time.mktime(datetime.now().timetuple())
would rather work.
But, to make it short, time.time(), as explicitly stated in the spec, returns an UTC timestamp, so just use it.
(Also, you don't need pytz to get an UTC datetime, datetime.utcnow() does the same)
try:
now_utc.time().strftime(....)
from here

Change datetime to Unix time stamp in Python

Please help me to change datetime object (for example: 2011-12-17 11:31:00-05:00) (including timezone) to Unix timestamp (like function time.time() in Python).
Another way is:
import calendar
from datetime import datetime
d = datetime.utcnow()
timestamp=calendar.timegm(d.utctimetuple())
Timestamp is the unix timestamp which shows the same date with datetime object d.
import time
import datetime
dtime = datetime.datetime.now()
ans_time = time.mktime(dtime.timetuple())
Incomplete answer (doesn't deal with timezones), but hopefully useful:
time.mktime(datetime_object.timetuple())
** Edited based on the following comment **
In my program, user enter datetime, select timezone. ... I created a timezone list (use pytz.all_timezones) and allow user to chose one timezone from that list.
Pytz module provides the necessary conversions. E.g. if dt is your datetime object, and user selected 'US/Eastern'
import pytz, calendar
tz = pytz.timezone('US/Eastern')
utc_dt = tz.localize(dt, is_dst=True).astimezone(pytz.utc)
print calendar.timegm(utc_dt.timetuple())
The argument is_dst=True is to resolve ambiguous times during the 1-hour intervals at the end of daylight savings (see here http://pytz.sourceforge.net/#problems-with-localtime).

Python DateUtil Converting string to a date and time

I'm trying to convert a parameter of type string to a date time. I'm using the dateUtil library
from dateutil import parser
myDate_string="2001/9/1 12:00:03"
dt = parser.parse(myDate_string,dayfirst=True)
print dt
every time i run this i get
2001-09-01 12:00:03
regardless of whether i have dayfirst set as true or Year first set as false. Ideally I just want to have a date in the format DD-MM-YYYY HH:MM:SS. I don't want anything fancy. I am willing to use the datetime library but this doesn't seem to work at all for me. Can anyone give simple expamples of how to convert strings to date time with an explicit format, I'm a noob, so the most basic examples are all i require. I'm using Python 2.7
The problem you're having is that any arguments you pass to parser.parse only affect how the string is parsed, not how the subsequent object is printed.
parser.parse returns a datetime object - when you print it it will just use datetime's default __str__ method. If you replace your last line with
print dt.strftime("%d-%m-%Y %H:%M:%S")
it will work as you expect.
The standard lib (built-in) datetime lib can do this easily.
from datetime import datetime
my_date_string = "2001/9/1 12:00:03"
d = datetime.strptime(my_date_string, "%Y/%m/%d %H:%M:%S")
print d.strftime("%d-%m-%Y %H:%M:%S")

Categories

Resources