Guest User

default datetime column

a guest
Mar 4th, 2016
1,365
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import datetime
  2. import time
  3. from sqlalchemy import create_engine, Column, Integer, DateTime
  4. from sqlalchemy.ext.declarative import declarative_base
  5. from sqlalchemy.orm import sessionmaker
  6.  
  7. DeclarativeBase = declarative_base()
  8.  
  9. class Test(DeclarativeBase):
  10.     __tablename__ = 'test'
  11.  
  12.     id = Column(Integer, primary_key=True)
  13.     created = Column(DateTime, default=datetime.datetime.utcnow)
  14.  
  15. # Prepare database and session
  16.  
  17. engine = create_engine('sqlite://', echo=False)
  18. DeclarativeBase.metadata.create_all(engine)
  19. session_maker = sessionmaker(engine)
  20. session = session_maker()
  21.  
  22. # Test
  23.  
  24. t = Test()
  25. session.add(t)
  26. session.flush()
  27.  
  28. time.sleep(1)
  29.  
  30. t2 = Test()
  31. session.add(t2)
  32. session.flush()
  33.  
  34. print(t.created)
  35. print(t2.created)
RAW Paste Data