Showing posts with label python_datetime_strftime. Show all posts
Showing posts with label python_datetime_strftime. Show all posts

Feb 12, 2019

Python csv write

from users.models import *
import sys

up = UserProfile.objects.all()
print up.count()

header = "Name, User Type, Email, Phone, City, Country, TimeZone, Created Date\n"

fname = "/tmp/user_data.csv"
with open(fname, 'w') as FW:
   FW.write(header)
   for each in up:
     try:
        name = each.name
        name = name.encode('utf-8').strip()
        dts = each.created_date
        dts = dts.strftime("%d %b %Y") #dts.strftime("%b %d %Y %I:%M %p")
        str1 = "%s,%s,%s,%s,%s,%s,%s,%s\n" % (str(name), str(each.usertype), str(each.email_id), str(each.phone), str(each.city), str(each.country), str(each.timezone), str(dts))
        #print str1
        FW.write(str1)
     except Exception, e:
        print '---- Error: ' + str(e)

print fname


Output:
Name, User Type, Email, Phone, City, Country, TimeZone, Created Date
User2,Student,user2@abc.com,None,Bangalore,IN,Asia/Kolkata,16 Mar 2018
User3,Student,user3@gmail.com,None,Pune,IN,Asia/Kolkata,28 Mar 2018
....


Jan 25, 2019

Python datetime

from datetime import datetime

datetime_obj = datetime.now() 
print datetime_obj #2019-01-25 13:45:28.087000
print datetime_obj.date() #2019-01-25
print datetime_obj.year  #2019
print datetime_obj.month #1
print datetime_obj.day   #25
print datetime_obj.hour  #13
print datetime_obj.minute #45
print datetime_obj.second #28

datetime_object = datetime(2011, 07, 01, 11, 50, 55)
print datetime_object
datetime_object_str =  datetime_object.strftime("%Y-%m-%d %H:%M:%S")
print datetime_object_str #2011-07-01 11:50:55
print type(datetime_object_str) #<type 'str'>

datetime_object = datetime.strptime('2018-07-11 10:55:55', '%Y-%m-%d %H:%M:%S')
print datetime_object #2011-07-01 11:50:55
print type(datetime_object) #<type 'datetime'>